下图显示了房屋街区的航拍照片(重新定向,最长边垂直),并且同一图像经过自适应阈值和高斯差分。
Images: Base; Adaptive Thresholding; Difference of Gaussians
在 AdThresh 图像上,房屋的屋顶印花很明显(对人眼而言):这是将一些明显的点连接起来的问题。在示例图像中,找到下面的蓝色边界框 -
Image with desired rectangle marked in blue
我在实现 HoughLinesP()
和 findContours()
时遇到了困难,但没有任何明智的做法(可能是因为我遗漏了一些细微差别)。像蓝框一样远程找不到任何东西的python脚本块如下:
import cv2
import numpy as np
from matplotlib import pyplot as plt
# read in full (RGBA) image - to get alpha layer to use as mask
img = cv2.imread('rotated_12.png', cv2.IMREAD_UNCHANGED)
grey = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
# Otsu's thresholding after Gaussian filtering
blur_base = cv2.GaussianBlur(grey,(9,9),0)
blur_diff = cv2.GaussianBlur(grey,(15,15),0)
_,thresh1 = cv2.threshold(grey,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)
thresh = cv2.adaptiveThreshold(grey,255,cv2.ADAPTIVE_THRESH_GAUSSIAN_C, cv2.THRESH_BINARY,11,2)
DoG_01 = blur_base - blur_diff
edges_blur = cv2.Canny(blur_base,70,210)
# Find Contours
(ed, cnts,h) = cv2.findContours(grey, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
cnts = sorted(cnts, key = cv2.contourArea, reverse = True)[:4]
for c in cnts:
approx = cv2.approxPolyDP(c, 0.1*cv2.arcLength(c, True), True)
cv2.drawContours(grey, [approx], -1, (0, 255, 0), 1)
# Hough Lines
minLineLength = 30
maxLineGap = 5
lines = cv2.HoughLinesP(edges_blur,1,np.pi/180,20,minLineLength,maxLineGap)
print "lines found:", len(lines)
for line in lines:
cv2.line(grey,(line[0][0], line[0][1]),(line[0][2],line[0][3]),(255,0,0),2)
# plot all the images
images = [img, thresh, DoG_01]
titles = ['Base','AdThresh','DoG01']
for i in xrange(len(images)):
plt.subplot(1,len(images),i+1),plt.imshow(images[i],'gray')
plt.title(titles[i]), plt.xticks([]), plt.yticks([])
plt.savefig('a_edgedetect_12.png')
cv2.destroyAllWindows()
我试图在没有过多参数化的情况下进行设置。我对仅针对这一张图像“定制”算法持谨慎态度,因为此过程将在数十万张图像上运行(具有不同颜色的屋顶/屋顶,可能与背景难以区分)。也就是说,我很想看到一个“命中”蓝盒目标的解决方案——这样我至少可以弄清楚我做错了什么。
如果有人有一种快速而肮脏的方法来做这种事情,那么获得一个 Python 代码片段会很棒。
“基础”图像 ->
Base Image
最佳答案
您应该应用以下内容:
1. Contrast Limited Adaptive Histogram Equalization-CLAHE 并转换为灰度。
2.@bad_keypoints 提到的高斯模糊和 Morphological transforms(扩张、侵 eclipse 等)。这将帮助您摆脱背景噪音。这是最棘手的步骤,因为结果将取决于您应用的顺序(首先是高斯模糊,然后是形态变换,反之亦然)以及您为此目的选择的窗口大小。
3. 应用自适应阈值
4. 应用 Canny 的边缘检测
5. 找到有四个角点的轮廓
如前所述,您需要调整这些函数的输入参数,还需要使用其他图像验证这些参数。因为它可能适用于这种情况,但不适用于其他情况。根据反复试验,您需要修复参数值。
关于python - OpenCV (Python) : Construct Rectangle from thresholded image,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31039348/