在Python中使用OpenCV遍历图像分段

0 投票
1 回答
805 浏览
提问于 2025-04-18 13:30

我正在尝试写一段代码,用来计算图像中黄瓜甲虫的数量,使用的是opencv这个库。我用的测试图像可以在这里找到:

http://bangordailynews.com/wp-content/uploads/2011/07/reeser730b-600x450.jpg

下面的代码在分离每只甲虫或甲虫群体方面做得不错,它利用了甲虫独特的黑黄条纹,并用红色圈住它们。不过,现在我想进一步分析每个被红色圈住的区域,以确定每个区域里有多少只甲虫,可能通过识别一些特征,比如黑色的头部或黄色的胸部。那么问题是,我该如何分离和遍历这些区域,以便进行进一步处理呢?

祝一切顺利,

科林

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)

1 个回答

0

我来告诉你我会怎么做。我试过你的代码,发现 threshbs.jpg 的效果还不错。

  • 在这个图片上找轮廓。用 CV_RETR_EXTERNAL 方法。
  • 一个一个地填充每个轮廓,使用 CV_FILL。用 drawContour 来画出轮廓,记得用轮廓的索引。
  • bitwise_and 把它和原始图片做个“与”运算。这样,你的图片里就只会有一个轮廓了。你就得到了你想要的部分,可以继续处理。
  • 在一张新的图片上画第二个轮廓,重复这个过程。

撰写回答