gpt4 book ai didi

python - 从阈值图像opencv python中去除噪声

转载 作者:太空狗 更新时间:2023-10-29 17:28:05 25 4
gpt4 key购买 nike

我正在尝试获取图像中的框角。以下是示例图像,它们的阈值结果和箭头后面的右侧是我需要的结果。您之前可能在 slack 上也看过这些图片,因为我将这些图片用于我在 slack 上的示例问题。

enter image description here

以下是允许我到达中间图像的代码。

import cv2
import numpy as np

img_file = 'C:/Users/box.jpg'
img = cv2.imread(img_file, cv2.IMREAD_COLOR)
img = cv2.blur(img, (5, 5))

hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
h, s, v = cv2.split(hsv)

thresh0 = cv2.adaptiveThreshold(s, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
thresh1 = cv2.adaptiveThreshold(v, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
thresh2 = cv2.adaptiveThreshold(v, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY_INV, 11, 2)
thresh = cv2.bitwise_or(thresh0, thresh1)

cv2.imshow('Image-thresh0', thresh0)
cv2.waitKey(0)
cv2.imshow('Image-thresh1', thresh1)
cv2.waitKey(0)
cv2.imshow('Image-thresh2', thresh2)
cv2.waitKey(0)

opencv 中是否有任何方法可以为我做这件事。我尝试了扩张 cv2.dilate() 和侵 eclipse cv2.erode() 但它在我的案例中不起作用。或者如果不行,那么可以采用其他替代方法它 ?谢谢

图像的 Canny 版本......左边是低阈值,右边是高阈值

enter image description here

最佳答案

下面是@dhanushka 方法的 python 实现

import cv2
import numpy as np

# load color image
im = cv2.imread('input.jpg')

# smooth the image with alternative closing and opening
# with an enlarging kernel
morph = im.copy()

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (1, 1))
morph = cv2.morphologyEx(morph, cv2.MORPH_CLOSE, kernel)
morph = cv2.morphologyEx(morph, cv2.MORPH_OPEN, kernel)

kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (2, 2))

# take morphological gradient
gradient_image = cv2.morphologyEx(morph, cv2.MORPH_GRADIENT, kernel)

# split the gradient image into channels
image_channels = np.split(np.asarray(gradient_image), 3, axis=2)

channel_height, channel_width, _ = image_channels[0].shape

# apply Otsu threshold to each channel
for i in range(0, 3):
_, image_channels[i] = cv2.threshold(~image_channels[i], 0, 255, cv2.THRESH_OTSU | cv2.THRESH_BINARY)
image_channels[i] = np.reshape(image_channels[i], newshape=(channel_height, channel_width, 1))

# merge the channels
image_channels = np.concatenate((image_channels[0], image_channels[1], image_channels[2]), axis=2)

# save the denoised image
cv2.imwrite('output.jpg', image_channels)

如果您处理的图像是发票(或在白色背景上有大量文本),则上述代码不会给出好的结果。为了在此类图像上获得良好的效果,请删除

gradient_image = cv2.morphologyEx(morph, cv2.MORPH_GRADIENT, kernel)

并将morph obj传递给split函数并移除for循环中的~符号

关于python - 从阈值图像opencv python中去除噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42065405/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com