0

使用的图像——

在此处输入图像描述

我的代码:

# 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 的输出相同。

为什么?错误是什么?如果它正在覆盖以前的功能,那么我如何显示每个功能?

请帮忙。谢谢 :)

4

1 回答 1

1

您每次都在同一图像中进行更改。cv2.drawContours(img.copy ,.......)在,中使用 image.copy() cv2.rectangle(img.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()

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

于 2018-06-19T15:27:28.443 回答