Opencv角点检测

时间:2016-11-06 10:49:51

标签: python opencv corner-detection

我有这样的图像:

enter image description here

当我尝试使用任何角落检测算法时,我都会遇到这样的问题:

enter image description here

但是我想要矩形的角落。

我怎样才能摆脱那些我不想要的角落。

这是我的代码

import cv2
import numpy as np
from matplotlib import pyplot as plt

img = cv2.imread("/home/mkmeral/Desktop/opencv/cropped.png")

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
corners = cv2.goodFeaturesToTrack(gray,4,0.01,10)
corners = np.int0(corners)

for i in corners:
    x,y = i.ravel()
    cv2.circle(img,(x,y),3,255,-1)

plt.subplot(121),plt.imshow(img)
plt.title('2'), plt.xticks([]), plt.yticks([])
plt.suptitle("CORNERS")

cv2.imwrite("/home/mkmeral/Desktop/opencv/corners.png", img)

plt.show()

这是整个图像,我裁剪图像使其变小。

enter image description here

这是我需要角落的地方:

enter image description here

2 个答案:

答案 0 :(得分:1)

由于你的图像分辨率相当差并且与矩形相似,所以任何解决方案都会在旁观者看来。

您可以使用 OpenCV 执行此操作,但我只是在命令行使用 ImageMagick 解释该方法。因此,将图像阈值设置为50%黑白,然后执行“Blob分析”“连接组件分析”

convert rect.png -threshold 50%              \
   -define connected-components:verbose=true \
   -connected-components 8 result.png

<强>输出

Objects (id: bounding-box centroid area mean-color):
  0: 160x120+0+0 78.0,58.7 18551 srgb(0,0,0)
  1: 52x50+97+58 121.8,82.6 649 srgb(255,255,255)

所以,如果我们看最后一行,我们有一个52x50像素的区域,面积为649像素,颜色为白色 - 这就是你的形状 - 或者像我想象的那样燃烧着香烟!让我们把它画进去:

convert rect.png -stroke red -fill none -draw "rectangle 97,58 148,107" y.png

enter image description here

现在,如果它是一个如你所说的矩形,它的长度大致等于封闭盒的对角线,所以

L = sqrt(52*52 + 50*50) = 72

,其面积为649,因此其宽度约为9像素,从左上角开始为+ 97 + 58。或者它的质心是121.8,82.6。所以,所需要的只是一个小学生几何学来获得你的角点。

答案 1 :(得分:0)

我发现通过调整传递给cv2.cornerHarris()的参数,我可以正确识别角点。

E.g。给出这个输入图像:

enter image description here

我们可以使用以下内容捕获角落(请注意传递给cornerHarris()的参数:

import cv2
import numpy as np
from matplotlib import pyplot as plt

img_file = 'a.jpg'

img = cv2.imread(img_file, 0)
img = np.float32(img)

'''args:
img - Input image, it should be grayscale and float32 type.
blockSize - It is the size of neighbourhood considered for corner detection
ksize - Aperture parameter of Sobel derivative used.
k - Harris detector free parameter in the equation.
'''
corners = cv2.cornerHarris(img, 4, 3, 0.04)
corners2 = cv2.dilate(corners, None, iterations=3)

img2 = cv2.imread(img_file)
img2[corners2>0.01*corners2.max()] = [255,0,0]

plt.subplot(2, 1, 2)
plt.imshow(img2, cmap = 'gray')
plt.title('Canny Edge Detection')
plt.xticks([])
plt.yticks([])
plt.show()

输出:

enter image description here

相关问题