如何使用OpenCV和Python在图像上找到边界坐标



我必须自动找到边界(对象(开始的坐标(只有一点(,我不知道如何处理函数findContours。

testImage.jpg


image = cv2.imread("testImage.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Threshold
ret, thresh = cv2.threshold(gray,225,255,0)
# Contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
# Here are coordinates that I have to find out
coord = contours[0][1]
# Coordinates to point
point = (coord[0][0],coord[0][1])
# Draw circle on coordinates
cv2.circle(image,point,10,(0,255,0),1)
cv2.imshow("Image", image)
cv2.waitKey()
cv2.destroyAllWindows() 

输出

我的目标是找出边界上任何地方的坐标(蓝线(——见最后一张图片。

目标

谢谢。

我稍微调整了一下您的代码。它似乎起了作用。看看它是否有帮助:

import cv2
import numpy as np
image = cv2.imread("test.jpg")
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
t = 230 # threshold: tune this number to your needs
# Threshold
ret, thresh = cv2.threshold(gray,t,255,cv2.THRESH_BINARY_INV)
#kernel = np.ones((9,9),np.uint8)
#thresh = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2.imshow("thresh", thresh)
cv2.waitKey(1)
# Contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# find the coordinate with the smallest x value
for contour in contours:
coord = min(contour[0], key=lambda c: c[0])
# Coordinates to point
point = (coord[0],coord[1])
#draw circles on coordinates
cv2.circle(image,point,10,(0,255,0),5)
cv2.imshow("Image", image)
cv2.waitKey()
cv2.destroyAllWindows() 

注意:增加参数t可将绿色圆圈移动到轮廓的"更外侧"。减小它可以向内移动。

@Sparkofska

谢谢你的想法,我用另一种方法来了解。


image = cv2.imread('testImage.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
t=230
ret, thresh = cv2.threshold(gray,t,255,cv2.THRESH_BINARY_INV)
cv2.imshow("filter", thresh)
# Canny Edge detection
canny = cv2.Canny(thresh, 0, 100)
cv2.imshow("canny", canny)
# Find contours
cnts = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)[-2:]
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
x, y, w, h = cv2.boundingRect(c)
# My coordinates
cv2.circle(image,(x,y), 10, (0,255,0), 5)
cv2.imshow("output", image)
cv2.waitKey()
cv2.destroyAllWindows() 

最新更新