简体   繁体   English

查找图像的轮廓Python OpenCV

[英]Finding Contours of an image Python OpenCV

# import the necessary packages
import decimal
import imutils
import cv2
import numpy as np
import matplotlib.pyplot as plt

# load the image, convert it to grayscale, and blur it slightly
image = cv2.imread("hand.jpg",0)

# threshold the image, then perform a series of erosions +
# dilations to remove any small regions of noise
thresh = cv2.threshold(image, 45, 255, cv2.THRESH_BINARY)[1]
thresh = cv2.erode(thresh, None, iterations=2)
thresh = cv2.dilate(thresh, None, iterations=2)

# find contours in thresholded image, then grab the largest one
cnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,
    cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if imutils.is_cv2() else cnts[1]
c = max(cnts, key=cv2.contourArea)
size = len(c);

refer_point = (207,130)

data = np.genfromtxt("data.txt", delimiter=',')

X = data[:,][:,0]

Y = data[:,][:,1]

for i in range(0,size):
    dist1= (((abs(207-X))**2)+((abs(130-Y))**2))**(1.0/2.0)

dist3 = round(dist1,2)
print dist3

plt.plot([dist3])

plt.show()

I am working on the above code. 我正在上面的代码。 The code was executed perfectly but the contour points of the image were completely wrong. 代码执行得很好,但是图像的轮廓点完全错误。 I observed this error after plotting the graph. 绘制图形后,我观察到此错误。 Help me on this issue. 帮助我解决这个问题。

1) If there is no kernel specified for erosion and dilation, the image does not change. 1)如果没有为腐蚀和膨胀指定内核,则图像不会改变。 Try them with a kernel. 尝试使用内核。

kernel = np.ones((3,3),np.uint8)
thresh = cv2.erode(thresh, kernel, iterations=1)
thresh = cv2.dilate(thresh, kernel, iterations=1)

2) cnts contains the points ((x,y) tuples) on the contour found. 2) cnts包含找到的轮廓上的点((x,y)元组)。 size is only the number of points on that contour. size只是该轮廓上的点数。 You acquire the size of it and do not process the points, instead you read a data file and plot something totally different. 您获得了它的大小并且不处理这些点,而是读取了一个数据文件并绘制了完全不同的东西。 To properly see the contours, try the following after findContours: 若要正确查看轮廓,请在findContours之后尝试以下操作:

# Load the image in color
image = cv2.imread("hand.jpg",cv2.IMREAD_COLOR)
# Draw the contours
cv2.drawContours(image, cnts, -1, (0,255,0), 3)
# Show the image with the contours
cv2.imshow("contours",image)

Then try to relate your data file with the contour points. 然后尝试将数据文件与轮廓点相关联。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM