使用 OpenCV 获取完整的形状模式

Obtain complete pattern of shapes with OpenCV

我正在编写一个脚本,使用不同的 OpenCV 操作来处理屋顶上带有太阳能电池板的图像。我的原图如下:

经过图像处理后,得到面板的边缘如下:

图中可以看到一些矩形由于太阳的反射而破碎

我想知道是否可以修复那些破损的矩形,也许可以使用未破损的图案。

我的代码如下:

# Load image
color_image = cv2.imread("google6.jpg")
cv2.imshow("Original", color_image)
# Convert to gray
img = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)

# Apply various filters
img = cv2.GaussianBlur(img, (5, 5), 0)
img = cv2.medianBlur(img, 5)
img = img & 0x88 # 0x88
img = cv2.fastNlMeansDenoising(img, h=10)

# Invert to binary
ret, thresh = cv2.threshold(img, 127, 255, 1) 

# Perform morphological erosion
kernel = np.ones((5, 5),np.uint8)
erosion = cv2.morphologyEx(thresh, cv2.MORPH_ERODE, kernel, iterations=2)

# Invert image and blur it
ret, thresh1 = cv2.threshold(erosion, 127, 255, 1)
blur = cv2.blur(thresh1, (10, 10))

# Perform another threshold on blurred image to get the central portion of the edge
ret, thresh2 = cv2.threshold(blur, 145, 255, 0)

# Perform morphological erosion to thin the edge by ellipse structuring element
kernel1 = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
contour = cv2.morphologyEx(thresh2, cv2.MORPH_ERODE, kernel1, iterations=2)

# Get edges
final = cv2.Canny(contour, 249, 250)
cv2.imshow("final", final)

我已经尝试修改我正在使用的所有滤镜,以尽可能减少原始图片中太阳的影响,但这是我所能做到的。

我对所有这些过滤器的结果总体上很满意(尽管欢迎任何建议),所以我想处理我展示的 black/white 图像,它已经足够平滑了post-我需要做的处理。

谢谢!

原始图像中的图案没有被破坏,所以它在你的二值化结果中被破坏一定意味着你的二值化不是最优的。

您应用 threshold() 对图像进行二值化,然后对二值图像应用 Canny()。这里的问题是:

  1. 阈值删除了很多信息,这应该始终是任何处理管道的最后一步。你在这里失去的任何东西,你都永远失去了。
  2. Canny() 应应用于 gray-scale 图像,而不是二进制图像。
  3. Canny 边缘检测器是一种边缘检测器,但您要检测的是线条,而不是边缘。请参阅 here 了解差异。

所以,我建议从头开始。

。我采取了这些步骤:

  1. 读入图像,转换为灰度。
  2. 应用 sigma = 2 的高斯拉普拉斯算子。
  3. 反转(否定)结果,然后将负值设置为 0。

这是输出:

从这里开始,应该比较straight-forward识别格子图案了

我不 post 编写代码,因为我为此使用了 MATLAB,但是您可以在 Python 中使用 OpenCV 完成相同的结果,here is a demo for applying the Laplacian of Gaussian in OpenCV


这是 Python + 复制以上内容的 OpenCV 代码:

import cv2

color_image = cv2.imread("/Users/cris/Downloads/L3RVh.jpg")
img = cv2.cvtColor(color_image, cv2.COLOR_BGR2GRAY)
out = cv2.GaussianBlur(img, (0, 0), 2)  # Note! Specify size of Gaussian by the sigma, not the kernel size
out = cv2.Laplacian(out, cv2.CV_32F)
_, out = cv2.threshold(-out, 0, 1e9, cv2.THRESH_TOZERO)

但是,从 BGR 转换为灰色时,OpenCV 似乎没有线性化(应用伽玛校正),因为我在创建上面的图像时使用了转换函数。我认为这种伽玛校正可能会通过减少对屋顶瓦片的响应来稍微改善结果。