轮廓-OpenCV错误:相同的输出用于不同的功能,例如船体,矩形

时间:2018-06-19 14:54:13

标签: python-3.x opencv opencv-contour opencv-python

使用的图片-

enter image description here

我的代码:

# multiple programs

import cv2
import numpy as np

img = cv2.imread('Dodo.jpg', 0)
ret, thresh = cv2.threshold(img, 127, 255, 0)
img2, contours, hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print(M)

cx = int(M['m10']/ M['m00'])
cy = int(M['m01']/ M['m00'])
print("Cx:", cx, "Cy:", cy)

area = cv2.contourArea(cnt)
print("Area:", area)
perimeter = cv2.arcLength(cnt, True)
print("Perimeter:", perimeter)

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
imgapprox = cv2.drawContours(img,[approx],0,(0,0,255),2)

hull = cv2.convexHull(cnt)
imghull =cv2.drawContours(img,[hull],0,(0,0,255),2)

k = cv2.isContourConvex(cnt)
print(k)

x,y,w,h = cv2.boundingRect(cnt)
rectst = cv2.rectangle(img,(x,y),(x+w,y+h),(0,255,0),2)


rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
rectrt =cv2.drawContours(img,[box],0,(0,0,255),2)

cv2.imshow('StraightRect', rectst)
cv2.imshow('RotatedRect', rectrt)
cv2.imshow('Approx', imgapprox)
cv2.imshow('hull', imghull)

cv2.waitKey()
cv2.destroyAllWindows()

OpenCV-Python版本3.4.1

所以我试图在OpenCV中学习轮廓部分(下面的链接)

链接:https://docs.opencv.org/3.4.1/dd/d49/tutorial_py_contour_features.html

现在,所有功能的输出均相同。也就是说,此处每个cv2.imshow的输出都相同。

为什么?有什么错误? 如果它覆盖了以前的功能,那么如何显示每个功能?

请帮助。谢谢:)

1 个答案:

答案 0 :(得分:1)

您每次都在同一张图像中进行更改。 在cv2.drawContours(img.copy ,.......)cv2.rectangle(img.copy(),.....)中使用image.copy() 因此,似乎它们显示的功能相同,但事实并非如此。 另外,由于背景为黑色,因此您无法正确看到矩形和轮廓线

尝试一下:

import cv2
import numpy as np

img = cv2.imread('Dodo.jpg')

f1 = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
f1 = cv2.threshold(f1, 120,255, cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

img2, contours, hierarchy = cv2.findContours(f1, cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_NONE)

#ret, thresh = cv2.threshold(img, 127, 255, 0)
#img2, contours, hierarchy = cv2.findContours(thresh, 1, 2)

cnt = contours[0]
M = cv2.moments(cnt)
print(M)

cx = int(M['m10']/ M['m00'])
cy = int(M['m01']/ M['m00'])
print("Cx:", cx, "Cy:", cy)

area = cv2.contourArea(cnt)
print("Area:", area)
perimeter = cv2.arcLength(cnt, True)
print("Perimeter:", perimeter)

epsilon = 0.1*cv2.arcLength(cnt,True)
approx = cv2.approxPolyDP(cnt,epsilon,True)
imgapprox = cv2.drawContours(img.copy(),[approx],0,(0,0,255),2)

hull = cv2.convexHull(cnt)
imghull =cv2.drawContours(img.copy(),[hull],0,(0,0,255),2)

k = cv2.isContourConvex(cnt)
print(k)

x,y,w,h = cv2.boundingRect(cnt)
rectst = cv2.rectangle(img.copy(),(x,y),(x+w,y+h),(0,255,0),2)


rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
rectrt =cv2.drawContours(img.copy(),[box],0,(0,0,255),2)

cv2.imshow('StraightRect', rectst)
cv2.imshow('RotatedRect', rectrt)
cv2.imshow('Approx', imgapprox)
cv2.imshow('hull', imghull)

cv2.waitKey()
cv2.destroyAllWindows()

这是我执行上述代码后得到的结果。 Result