在python中用opencv迭代图像段

2024-05-07 00:42:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试用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)

Tags: andtoimporttargetnpcv2jpgcopy
1条回答
网友
1楼 · 发布于 2024-05-07 00:42:28

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

  • 找到轮廓。使用外部简历。在
  • 使用CV_Fill一次填充一个计数器。drawContour轮廓索引。在
  • bitwise_and它与原始图像。现在,图像中只有一个轮廓。你有你的斑点。做进一步的处理。在
  • 在新图像上绘制第二个轮廓。重复。在

相关问题 更多 >