我正在尝试编写一个可以用opencv计算图像中黄瓜甲虫数量的代码。我正在使用的测试图像可在此处获取:
http://bangordailynews.com/wp-content/uploads/2011/07/reeser730b-600x450.jpg
下面的代码可以通过使用独特的黄色和黑色条纹隔离单个甲虫或甲虫簇,并用红色环绕它们。然而,在这一点上,我希望能够进一步分析每个封闭的红色斑点,以便能够确定每个斑点中有多少甲虫,可能通过使用识别特征,如黑头或黄色胸腔。所以问题是,我如何隔离和迭代blob以进行进一步处理?
一切顺利, 科林
import cv2
import numpy as np
from copy import copy
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE,(5,5))
#load file
target = cv2.imread('mcb3.jpg')
#convert to hsv and gray for procesing
hsvt = cv2.cvtColor(target,cv2.COLOR_BGR2HSV)
gray = cv2.cvtColor(target,cv2.COLOR_BGR2GRAY)
#Bounds for yellowish colors
lower_y = np.array([18,0,0],dtype=np.uint8)
upper_y = np.array([30,255,255],dtype=np.uint8)
#Make colors in yellowish range black and all others white to find yellow stripes
threshy = 255-cv2.inRange(hsvt, lower_y, upper_y)
cv2.imwrite('threshy.jpg',threshy)
#Make dark colors black and all others white to find dark stripes
ret, threshg = cv2.threshold(gray,30,255,cv2.THRESH_BINARY)
cv2.imwrite('threshg.jpg',threshg)
#merge black and yellow stripes
thresh = copy(threshg)
thresh[threshy == 0] = 0
thresh = 255-thresh
cv2.imwrite('thresh.jpg',thresh)
#Blur and threshold to smooth
thresh = cv2.blur(thresh,(30,30))
ret, thresh = cv2.threshold(thresh,100,255,cv2.THRESH_BINARY)
cv2.imwrite('threshbs.jpg',thresh)
#Get edges and draw in red on original image
edges = cv2.Canny(thresh,100,200)
edges[edges != 255] = 0
edges = cv2.dilate(edges, None)
target[edges == 255] = (0, 0, 255)
cv2.imwrite("res.jpg", target)
答案 0 :(得分:0)
这就是我的所作所为。我试用了你的代码,threshbs.jpg
非常好。
drawContour
。bitwise_and
它与原始图像。现在,您在图像中只有一个轮廓。你有你的blob。做进一步处理。