我使用等高线找出了图像中所示的端点,但我没有得到这些点(p1,p2,p3,p4)的预期输出.你能帮我找出来吗?我还附上了我的输入图像如下. 谢谢.

import cv2
cropped_image=cv2.imread('croped_img.png')
# cropped_image=cv2.resize(cropped_image,(512,615))
original_ccropped_image=cropped_image.copy()
cnt= contours(cropped_image)

#####take points bbox for stright line
x_new,y_new,w_new,h_new = cv2.boundingRect(cnt)

#####take points bbox for rotated
rect = cv2.minAreaRect(cnt)
box = cv2.boxPoints(rect)
box = np.int0(box)
print(box)
cropped_image=cv2.drawContours(cropped_image,[box],0,(0,0,255),2)

My input image

enter image description here

推荐答案

正如 comments 中所提到的,您需要使用凸度缺陷.关于这一点的OpenCV教程可以找到here.

我在您的示例图像上try 了以下代码,它可以在您的测试图像上运行.

import cv2
import matplotlib.pyplot as plt

# Read the image, ignore conversions that I did here.
img= cv2.imread('img.png')
img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
_, img_gray = cv2.threshold(img_gray,150,255,cv2.THRESH_BINARY)

# Find contours
contours, hierarchy = cv2.findContours(img_gray, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)

# Find the convex hulls and defects, assuming there might exist more than one contour.
hull_list= []
defect_list= []
for i in range(len(contours)):
    hull = cv2.convexHull(contours[i], returnPoints= False)
    defects = cv2.convexityDefects(contours[i],hull)
    hull = cv2.convexHull(contours[i])
    hull_list.append(hull)
    defect_list.append(defects)

# Draw.
for idx, defects in enumerate(defect_list):
    cv2.drawContours(img, hull_list, idx, (255,0,0),2) # remove if you do not want the contour.
    for i in range(defects.shape[0]):
        s,e,_,d = defects[i,0]
        if d>512: # This filters places that are very close to be convex. Change it to zero and see what happens !!!!
            start = tuple(contours[idx][s][0])
            end = tuple(contours[idx][e][0])
            cv2.line(img,start,end,[0,255,0],2)

plt.imshow(img)
plt.show()

enter image description here

Python相关问答推荐

rame中不兼容的d类型

Excel图表-使用openpyxl更改水平轴与Y轴相交的位置(Python)

pyscript中的压痕问题

如果值发生变化,则列上的极性累积和

关于Python异步编程的问题和使用await/await def关键字

pandas:排序多级列

形状弃用警告与组合多边形和多边形如何解决

如何在turtle中不使用write()来绘制填充字母(例如OEG)

SQLAlchemy bindparam在mssql上失败(但在mysql上工作)

通过ManyToMany字段与Through在Django Admin中过滤

matplotlib图中的复杂箭头形状

如何在海上配对图中使某些标记周围的黑色边框

巨 Python :逆向猜谜游戏

如何过滤组s最大和最小行使用`transform`'

获取PANDA GROUP BY转换中的组的名称

如何将泛型类类型与函数返回类型结合使用?

如何在Airflow执行日期中保留日期并将时间转换为00:00

比较两个有条件的数据帧并删除所有不合格的数据帧

如何通过特定导入在类中执行Python代码

如何从具有完整层次数据的Pandas框架生成图形?