基于OpenCV的实战:轮廓检测(附代码解析)_OpenCV

利用轮廓检测物体可以看到物体的各种颜色,在这种情况下放置在静态和动态物体上。如果是统计图像,则需要将图像加载到程序中,然后使用OpenCV库,以便跟踪对象。每当在框架中检测到物体时,都会为该物体绘制轮廓,该轮廓将代表物体的轮廓。下一步是找到对象的质心,标识找到影像矩所需的质心坐标,图像力矩是图像像素强度的加权平均值。因此,我们考虑考虑轮廓内的区域以找到图像矩,如果轮廓中的图像矩变为M,则可以按以下方式计算质心的坐标:

cx = int(M ['m10'] / M ['m00'])
cy = int(M ['m01'] / M ['m00'])

获得质心点后,此质心点将表示对象这样就可以为与质心相对应的对象放置一个边界框。本次实验我们将使用橙色作为对象,首先我们需要安装打包的OpenCV和numpy软件包。

  •  
import cv2import numpy as np

插入图片使用“ cv2.imread()”:

  •  
#Read Picturesimg = cv2.imread('jeruk.png')

然后将RGB转换为HSV并创建黄色(橙色为右黄色)颜色分割:

  •  
#Convert RGB to HSVhsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)#Range of yellow color segmentation / classificationlower = np.array([20,100,100], dtype=np.uint8)upper = np.array([40,255,255], dtype=np.uint8)mask = cv2.inRange(hsv, lower, upper)kernel = np.ones((25,25),np.uint8)

进行对象像素的增厚,然后减小尺寸,以使对象像素彼此不靠近:

  •  
# Thicken object pixelsdilation = cv2.dilate(mask,kernel,iterations = 1)# Minimized the object pixels so they're not stick togethererosion = cv2.erode(img,kernel,iterations = 1)

找到橙色的轮廓和阵列:

  •  
#Find Contourscontours, hierarchy = cv2.findContours(dilation,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)#Array Contourscontour = []

然后将原始图像复制到“ resultImg”变量:

  •  
#copy the original image to "resultImg"resultImg = (img).copy()

对轮廓进行迭代:

  •  
#Iterationfor i in range(len(contours)):        #amount contours to cnt variable        cnt = contours[i]        #Looking for radius to drau circle        (x,y),radius = cv2.minEnclosingCircle(cnt)        #circle center        center = (int(x),int(y))        if(int(radius) > 1):            contour.append(cnt)            #draw the circle            resultImg = cv2.circle(resultImg,center,int(radius,(255,0,0),3)

最后一个阶段,显示检测结果的轮廓:

  •  
#displays resultscv2.imshow('image',resultImg)cv2.waitKey(0)cv2.destroyAllWindows()

输出结果:

基于OpenCV的实战:轮廓检测(附代码解析)_OpenCV_02

根据前面显示的橙色检测结果,可以通过轮廓检测橙色,该轮廓由橙色对象上存在蓝色圆圈标记。

— — 完 — —

 

 

 

基于OpenCV的实战:轮廓检测(附代码解析)_OpenCV_03

更多文章请关注《万象专栏》