简体   繁体   English

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

[英]How to find border coordinates on image using OpenCV and Python

I have to find out automatically coordinates (only one point) where border (object) begin, I do not know how to handle function findContours.我必须自动找出边界(对象)开始的坐标(只有一个点),我不知道如何处理 function findContours。

testImage.jpg测试图像.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() 

Output Output

And my goal is find out coordinates anywhere on the border (blue line) - see last image.我的目标是找出边界上任何地方的坐标(蓝线) - 见最后一张图片。

Goal目标

Thanks.谢谢。

I tweaked your code a little.我稍微调整了你的代码。 It seems to do the trick.它似乎可以解决问题。 Check out if it helps:检查它是否有帮助:

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() 

Note: Increase parameter t to move your green circle 'farther outside' of the contour.注意:增加参数t以将绿色圆圈移动到轮廓“更远”的位置。 Decrease it to move inside.减小它以向内移动。

@Sparkofska @Sparkofska

Thanks for your idea, I use it with another way to find out.谢谢你的想法,我用另一种方法来找出答案。


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() 

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

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