gpt4 book ai didi

python - 从非常嘈杂的二值阈值图像中过滤噪声

转载 作者:行者123 更新时间:2023-12-02 03:11:25 25 4
gpt4 key购买 nike

我希望能够分析下面的图像,获取线条并找到平均宽度。(我的副本要大得多〜5K x〜4K)由于阈值处理后出现所有噪音,无法进入下一步。

enter image description here

使用我的代码我能够做到这一点......

enter image description here

我的问题是线条之间有很多噪音,看起来像是压缩的噪音。

这是我的代码...

image = np.copy(origImg)
newImage = np.empty_like(image)

scale = 64

height = image.shape[0]
width = image.shape[1]

dH = int(height / scale)
dW = int(width / scale)

xi = int(dH)
yi = int(dW)

fragments = []
image = cv2.bilateralFilter(image,9,75,75)
image = cv2.medianBlur(image, 21)

for i in range(0,height,dH):
for j in range(0,width,dW):
fragment = image[i:i + int(dH), j:j + int(dW)]

fragment = cv2.adaptiveThreshold(fragment, 255, cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY, 31, 0)

fragments.append(fragment)

analyzed = com.stackArrayToImage(fragments)

nlabels, labels, stats, centroids = cv2.connectedComponentsWithStats(analyzed, None, None, None, 8, cv2.CV_32S)
sizes = stats[1:, -1]
img2 = np.zeros((labels.shape), np.uint8)

for i in range(0, nlabels - 1):
if sizes[i] >= 100:
img2[labels == i + 1] = 255

analyzed = cv2.bitwise_not(img2)

analyzed = cv2.erode(analyzed, np.ones((5, 5)), iterations=2)
analyzed = cv2.dilate(analyzed, np.ones((5, 5), np.uint8))

dis.plotImages([origImg], "Origional")
dis.plotImages([analyzed], "Analyzed")
dis.displayStart()

有什么办法可以消除噪音吗?

非常感谢!

最佳答案

您可以使用 cv2.contourArea 等值线区域过滤来消除一些噪声。 。这个想法是使用一些阈值区域进行过滤。如果轮廓通过此过滤器,那么我们可以通过用 cv2.drawContours 填充轮廓来消除噪声。 。使用二进制图像作为输入:

enter image description here

检测到的轮廓要删除绿色突出显示

enter image description here

结果

enter image description here

根据要去除的噪声量,可以调整阈值面积值

代码

import numpy as np
import cv2

# Load image, grayscale, Otsu's threshold
image = cv2.imread("1.png")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

# Find contours and filter using contour area
cnts = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
area = cv2.contourArea(c)
if area < 50:
cv2.drawContours(thresh, [c], -1, 0, -1)
cv2.drawContours(image, [c], -1, (36,255,12), -1)

result = 255 - thresh
cv2.imshow("image", image)
cv2.imshow("thresh", thresh)
cv2.imshow("result", result)
cv2.waitKey()

关于python - 从非常嘈杂的二值阈值图像中过滤噪声,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480473/

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