(附代碼&解析)實(shí)戰(zhàn)|基于OpenCV的輪廓檢測(cè)項(xiàng)目

cx = int(M ['m10'] / M ['m00'])
cy = int(M ['m01'] / M ['m00'])
獲得質(zhì)心點(diǎn)后,此質(zhì)心點(diǎn)將表示對(duì)象這樣就可以為與質(zhì)心相對(duì)應(yīng)的對(duì)象放置一個(gè)邊界框。本次實(shí)驗(yàn)我們將使用橙色作為對(duì)象,首先我們需要安裝打包的OpenCV和numpy軟件包。
import cv2import numpy as np
插入圖片使用“ cv2.imread()”:
#Read Picturesimg = cv2.imread('jeruk.png')
然后將RGB轉(zhuǎn)換為HSV并創(chuàng)建黃色(橙色為右黃色)顏色分割:
#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)
進(jìn)行對(duì)象像素的增厚,然后減小尺寸,以使對(duì)象像素彼此不靠近:
# 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 = []
然后將原始圖像復(fù)制到“ resultImg”變量:
#copy the original image to "resultImg"resultImg = (img).copy()
對(duì)輪廓進(jìn)行迭代:
for i in range(len(contours)):#amount contours to cnt variablecnt = contours[i](x,y),radius = cv2.minEnclosingCircle(cnt)center = (int(x),int(y))if(int(radius) > 1):contour.append(cnt)resultImg = cv2.circle(resultImg,center,int(radius,(255,0,0),3)
最后一個(gè)階段,顯示檢測(cè)結(jié)果的輪廓:
#displays resultscv2.imshow('image',resultImg)cv2.waitKey(0)cv2.destroyAllWindows()
輸出結(jié)果:

根據(jù)前面顯示的橙色檢測(cè)結(jié)果,可以通過(guò)輪廓檢測(cè)橙色,該輪廓由橙色對(duì)象上存在藍(lán)色圓圈標(biāo)記。
雙一流高校研究生團(tuán)隊(duì)創(chuàng)建 ↓
專(zhuān)注于目標(biāo)檢測(cè)原創(chuàng)并分享相關(guān)知識(shí) ?
整理不易,點(diǎn)贊三連!
評(píng)論
圖片
表情
