gpt4 book ai didi

python - OpenCV检测毛巾边距

转载 作者:太空宇宙 更新时间:2023-11-03 21:21:02 24 4
gpt4 key购买 nike

在此图像中找到毛巾的最低角(不是边缘)的最佳方法是什么(使用 python 和 OpenCV)?此外,毛巾颜色可以不同,但​​背景颜色始终相同。

towel

我需要这个角(最低的“真实”毛巾角): expected result

最佳答案

由于图像中大约有两种不同的颜色(前景和背景各一种),您可以将图像转换为 HSV 颜色空间并可视化每个单独的 channel 。

代码:

path = r'C:\Users\Desktop'
filename = 'towel.jpg'

img = cv2.imread(os.path.join(path, filename))
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #--- convert to HSV
cv2.imshow('hsv.jpg', hsv)
h = hsv[:,:,0]
cv2.imshow('h.jpg', h) #--- visualize the hue channel

enter image description here

ret, thresh = cv2.threshold(h, 0, 255, cv2.THRESH_OTSU + cv2.THRESH_BINARY_INV)
cv2.imshow('thresh1', thresh) #--- apply Otsu threshold on hue channel

enter image description here

请注意毛巾中央的白色 Blob ,必须将其移除。为此,我使用了形态学开运算。

kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(25, 25))
opening = cv2.morphologyEx(thresh, cv2.MORPH_OPEN, kernel)
cv2.imshow('fin', cv2.bitwise_not(opening))

enter image description here

编辑

OpenCV 提供了查找给定轮廓的顶角、底角、最右角和最左角的功能。我获得了最终结果图像的轮廓并找到了四个极值点。

代码:

im2, contours, hierarchy = cv2.findContours(cv2.bitwise_not(opening), cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)                #--- finding contours
cnt = contours[0] #--- since there is only one contour present

leftmost = tuple(cnt[cnt[:,:,0].argmin()][0])
rightmost = tuple(cnt[cnt[:,:,0].argmax()][0])
topmost = tuple(cnt[cnt[:,:,1].argmin()][0])
bottommost = tuple(cnt[cnt[:,:,1].argmax()][0])

print('The extreme points are leftmost: {}, rightmost: {}, topmost: {} and bottommost: {}'.format(leftmost, rightmost, topmost, bottommost))

The extreme points are leftmost: (32, 336), rightmost: (807, 439), topmost: (459, 12) and bottommost: (699, 743)

我还在原始图像的副本上标记了极值点:

img2 = img.copy()
cv2.circle(img2, leftmost, 5, (0, 255, 255), -1) #-- leftmost
cv2.circle(img2, rightmost, 5, (0, 255, 255), -1) #-- rightmost
cv2.circle(img2, topmost, 5, (0, 255, 255), -1) #-- topmost
cv2.circle(img2, bottommost, 5, (0, 255, 255), -1) #-- bottommost

enter image description here

关于python - OpenCV检测毛巾边距,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551439/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com