使用形状轮廓检测进行形状匹配

时间:2018-04-16 17:28:16

标签: python cv2

import numpy as np
import cv2

temp = cv2.imread('./image/star.jpg')
ret, temp_thre = cv2.threshold(temp, 100, 255,0)

cv2.imshow("store gray iamge",temp_thre)
cv2.waitKey(0)

_, contours, hierarchy = cv2.findContours(temp_thre, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)
temp_cont = sorted(contours, key=cv2.contourArea, reverse= True)

new_temp_cont = temp_cont[1]

tar = cv2.imread('./image/store.jpg')
tar_gray = cv2.cvtColor(tar, cv2.COLOR_BGR2GRAY)
tar_thr = cv2.threshold(tar_gray, 127, 255, 0)
_, contours, hierarchy = cv2.findContours(tar_thr, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)

for c in contours:
    match = cv2.matchShapes(new_temp_cont, c, 1, 0.0)
    print(match)
    if match < 0.15:
        closest_match = c
    else:
        closest_match = []
cv2.drawContours(tar, [closest_match], -1, (0,255,0),2)
cv2.imshow("output", tar)
cv2.waitKey(0)
cv2.destroyAllWindows()

这是我的代码,但我仍然无法纠正它。请帮助我。

到达此处的错误是:

C:\python36\python.exe C:/Users/shahid/PycharmProjects/untitled/segmentation_object_detection.py
OpenCV Error: Unsupported format or combination of formats ([Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only) in cvStartFindContours_Impl, file C:\projects\opencv-python\opencv\modules\imgproc\src\contours.cpp, line 199
Traceback (most recent call last):
  File "C:/Users/shahid/PycharmProjects/untitled/segmentation_object_detection.py", line 10, in <module>
    _, contours, hierarchy = cv2.findContours(temp_thre, cv2.RETR_LIST, cv2.CHAIN_APPROX_NONE)`enter code here`
cv2.error: C:\projects\opencv-python\opencv\modules\imgproc\src\contours.cpp:199: error: (-210) [Start]FindContours supports only CV_8UC1 images when mode != CV_RETR_FLOODFILL otherwise supports CV_32SC1 images only in function cvStartFindContours_Impl

1 个答案:

答案 0 :(得分:0)

您的图片中有太多的通道用于findContours,这需要单通道8位图像。以下是如何获取源图像的​​信息:

temp = cv2.imread('./image/star.jpg')
print('shape={}'.format(temp.shape))

如果形状中有2个元素,则图像为单个通道。如果是3,则第3个元素是通道数。

您需要将图像转换为单通道8位图像,例如:

gray = cv2.cvtColor(temp, cv2.COLOR_BGR2GRAY)