在白色背景(粘性陷阱)上检测苍蝇的轮廓,留下一些灰色污迹

问题描述 投票:0回答:1

因此,我试图在白色陷阱上检测苍蝇的轮廓,然后将它们裁剪成不同的照片。但是我正在陷阱上看到污迹的轮廓,并且没有发现一些苍蝇。我也不需要陷阱的绿色线。我的问题是,有什么方法可以确保我得到所有苍蝇的轮廓并且只有文件吗?

代码:

image = cv2.imread('test3.jpeg') 
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)  
ret,thresh = cv2.threshold(gray,100,255,cv2.THRESH_BINARY)
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)  
cv2.drawContours(image, contours, -1, (0, 255, 0), 3)  

示例图片

enter image description here

当前代码的结果

enter image description here

python image-processing cv2
1个回答
0
投票

使用将色彩空间转换为HSV和形态学操作:

import cv2

img1 = cv2.imread('flys.jpg')
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (6,6))
img=cv2.cvtColor(img1, cv2.COLOR_BGR2HSV)
mask=cv2.threshold(img1[:,:,2], 85, 255, cv2.THRESH_BINARY)[1] 
mask = cv2.dilate(mask, kernel, iterations = 2)
mask = cv2.erode(mask, kernel, iterations = 7)

mask=cv2.bitwise_not(mask)
output = cv2.connectedComponentsWithStats(mask, 4, cv2.CV_32S)
print('number of flies: ', output[0])
for i in range(1, output[0]):
    x,y,w,h,s=output[2][i]
    img_crop=img1[y:y+h, x:x+w,:]
    cv2.imwrite(str(i)+'_crop_fly.jpg', img_crop)
mask=cv2.cvtColor(mask,cv2.COLOR_GRAY2BGR)


mask[:,:,1]=0
dst = cv2.addWeighted(img1, 0.7, mask, 0.3, 0.0)
cv2.imshow('test', dst)
cv2.imwrite('out_fly.jpg', dst)

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.