在python中使用opencv迭代图像段

在python中使用opencv迭代图像段,python,opencv,Python,Opencv,我正在尝试编写一个代码,可以用opencv计算图像中黄瓜甲虫的数量。我正在使用的测试图像可在此处获得: 下面的代码很好地隔离了单个甲虫或甲虫群,使用它们独特的黄色和黑色条纹,并用红色包围它们。然而,在这一点上,我希望能够进一步分析每个封闭的红色斑点,以确定每个斑点中有多少甲虫,也许可以通过使用识别特征,如黑色头部或黄色胸部。所以问题是,我如何隔离和迭代blob以进行进一步处理 祝你一切顺利, 科林 这是我要做的。我试用了你的代码,而且threshbs.jpg相当不错 在那个图像上找到轮廓。使

我正在尝试编写一个代码,可以用opencv计算图像中黄瓜甲虫的数量。我正在使用的测试图像可在此处获得:

下面的代码很好地隔离了单个甲虫或甲虫群,使用它们独特的黄色和黑色条纹,并用红色包围它们。然而,在这一点上,我希望能够进一步分析每个封闭的红色斑点,以确定每个斑点中有多少甲虫,也许可以通过使用识别特征,如黑色头部或黄色胸部。所以问题是,我如何隔离和迭代blob以进行进一步处理

祝你一切顺利, 科林


这是我要做的。我试用了你的代码,而且
threshbs.jpg
相当不错

  • 在那个图像上找到轮廓。使用CV_RETR_外部
  • 使用CV_填充每个计数器,每次填充一个<代码>绘制等高线带等高线索引
  • 按位_和
    将其与原始图像合并。现在,图像中只有一个轮廓。你有你的斑点。做进一步的处理
  • 在新图像上绘制第二个轮廓。重复一遍
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)