重磅干貨,第一時間送達
cx = int(M ['m10'] / M ['m00'])
cy = int(M ['m01'] / M ['m00'])
獲得質(zhì)心點后,此質(zhì)心點將表示對象這樣就可以為與質(zhì)心相對應(yīng)的對象放置一個邊界框。本次實驗我們將使用橙色作為對象,首先我們需要安裝打包的OpenCV和numpy軟件包。
import cv2
import numpy as np
插入圖片使用“ cv2.imread()”:
#Read Pictures
img = cv2.imread('jeruk.png')
然后將RGB轉(zhuǎn)換為HSV并創(chuàng)建黃色(橙色為右黃色)顏色分割:
#Convert RGB to HSV
hsv = cv2.cvtColor(img,cv2.COLOR_BGR2HSV)
#Range of yellow color segmentation / classification
lower = 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 pixels
dilation = cv2.dilate(mask,kernel,iterations = 1)
# Minimized the object pixels so they're not stick together
erosion = cv2.erode(img,kernel,iterations = 1)
找到橙色的輪廓和陣列:
#Find Contours
contours, hierarchy = cv2.findContours(dilation,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
#Array Contours
contour = []
然后將原始圖像復(fù)制到“ resultImg”變量:
#copy the original image to "resultImg"
resultImg = (img).copy()
對輪廓進行迭代:
#Iteration
for 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)
最后一個階段,顯示檢測結(jié)果的輪廓:
#displays results
cv2.imshow('image',resultImg)
cv2.waitKey(0)
cv2.destroyAllWindows()
輸出結(jié)果:
根據(jù)前面顯示的橙色檢測結(jié)果,可以通過輪廓檢測橙色,該輪廓由橙色對象上存在藍色圓圈標(biāo)記。
— — 完 — —
聯(lián)系客服