gpt4 book ai didi

python - Opencv 提取最大感兴趣区域

转载 作者:行者123 更新时间:2023-12-02 17:41:47 25 4
gpt4 key购买 nike

我有几个如下所示的图像:
图像大多在白色背景上。
有多件衣服放在白色(大部分)背景上。
enter image description here enter image description here
我尝试使用 opencv 连接组件检测这两件衣服。
试图采用最大的两个连接组件,不幸的是,我失败了。
我相信这是可能的,但由于我是 opencv 的新手,有人可以说明如何检测以下图像中的多件衣服吗?
任何帮助表示赞赏
我在python中尝试过的代码:

#Read the image and conver to grayscale
img = cv2.imread('t.jpg' , 0)
#Applt the median filter on the image
#med = cv2.medianBlur(image,5) # 5 is a fairly small kernel size
#Apply an edge detection filter

laplacian = cv2.Laplacian(img,cv2.CV_64F)

laplacian = laplacian.astype(np.uint8)
ret,thresh1 = cv2.threshold(laplacian,127,255,cv2.THRESH_BINARY)
src = thresh1
src = np.array(src, np.uint8)
ret, thresh = cv2.threshold(src,10,255,cv2.THRESH_BINARY)
# You need to choose 4 or 8 for connectivity type
connectivity =8
# Perform the operation
output = cv2.connectedComponentsWithStats(thresh, connectivity, cv2.CV_32S)
# Get the results
# The first cell is the number of labels
num_labels = output[0]
# The second cell is the label matrix
labels = output[1]
# The third cell is the stat matrix
stats = output[2]
# The fourth cell is the centroid matrix
centroids = output[3]
src = cv2.cvtColor(src,cv2.COLOR_GRAY2RGB)
for stat in stats:
x , y ,w , h ,a = stat
cv2.rectangle(src,(x,y),(x+w,y+h),(0,0,255),2)
# write original image with added contours to disk
#cv2.imwrite('contoured.jpg', image)
cv2.imshow("Image", src)
#cv2.waitKey(0)
cv2.waitKey(0)
cv2.destroyAllWindows()
我对上述代码的输出
enter image description here
注意 :即使我可以提取给定图像中最大的对象,它也很好。

最佳答案

这是一个非常简单的方法,只使用图像阈值处理和寻找轮廓来提取第二张照片中最大的衣服。要获得其他项目,您只需调整阈值以使其不会被清除,然后您将搜索轮廓。不是最好的解决方案,但它是一个开始。

img = cv2.imread('t.jpg' , 0) # import image as grayscale array

# threshold image
img_b = cv2.GaussianBlur(img, (13, 13), 2)
ret, img_th = cv2.threshold(img_b, 40, 255, cv2.THRESH_BINARY_INV)
# find contours
(_,cnts,_) = cv2.findContours(img_th.copy(), cv2.RETR_TREE,
cv2.CHAIN_APPROX_SIMPLE)
print(str(len(cnts))+' contours detected')

# find maximum area contour
area = np.array([cv2.contourArea(cnts[i]) for i in range(len(cnts))]) #
list of all areas
maxa_ind = np.argmax(area) # index of maximum area contour

plt.figure(figsize=(10,4))
plt.subplot(1,3,1)
plt.imshow(img_b)
plt.title('GaussianBlurr')
plt.subplot(1,3,2)
plt.imshow(img_th)
plt.title('threshold')
plt.subplot(1,3,3)
xx = [cnts[maxa_ind][i][0][0] for i in range(len(cnts[maxa_ind]))]
yy = [cnts[maxa_ind][i][0][1] for i in range(len(cnts[maxa_ind]))]
ROI.append([min(xx),max(xx),min(yy),max(yy)])
plt.imshow(img)
plt.plot(xx,yy,'r',linewidth=3)
plt.title('largest contour')

此代码生成以下图像:

enter image description here

关于python - Opencv 提取最大感兴趣区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43718211/

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