# -*- coding:utf-8 -*-__author__ = 'kingking'__version__ = '1.0'__date__ = '14/07/2017'import cv2import numpy as npimport timeif __name__ == '__main__': Img = cv2.imread('example.png')#讀入一幅圖像 kernel_2 = np.ones((2,2),np.uint8)#2x2的卷積核 kernel_3 = np.ones((3,3),np.uint8)#3x3的卷積核 kernel_4 = np.ones((4,4),np.uint8)#4x4的卷積核 if Img is not None:#判斷圖片是否讀入 HSV = cv2.cvtColor(Img, cv2.COLOR_BGR2HSV)#把BGR圖像轉(zhuǎn)換為HSV格式 ''' HSV模型中顏色的參數(shù)分別是:色調(diào)(H),飽和度(S),明度(V) 下面兩個(gè)值是要識(shí)別的顏色范圍 ''' Lower = np.array([20, 20, 20])#要識(shí)別顏色的下限 Upper = np.array([30, 255, 255])#要識(shí)別的顏色的上限 #mask是把HSV圖片中在顏色范圍內(nèi)的區(qū)域變成白色,其他區(qū)域變成黑色 mask = cv2.inRange(HSV, Lower, Upper) #下面四行是用卷積進(jìn)行濾波 erosion = cv2.erode(mask,kernel_4,iterations = 1) erosion = cv2.erode(erosion,kernel_4,iterations = 1) dilation = cv2.dilate(erosion,kernel_4,iterations = 1) dilation = cv2.dilate(dilation,kernel_4,iterations = 1) #target是把原圖中的非目標(biāo)顏色區(qū)域去掉剩下的圖像 target = cv2.bitwise_and(Img, Img, mask=dilation) #將濾波后的圖像變成二值圖像放在binary中 ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY) #在binary中發(fā)現(xiàn)輪廓,輪廓按照面積從小到大排列 contours, hierarchy = cv2.findContours(binary,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE) p=0 for i in contours:#遍歷所有的輪廓 x,y,w,h = cv2.boundingRect(i)#將輪廓分解為識(shí)別對(duì)象的左上角坐標(biāo)和寬、高 #在圖像上畫(huà)上矩形(圖片、左上角坐標(biāo)、右下角坐標(biāo)、顏色、線(xiàn)條寬度) cv2.rectangle(Img,(x,y),(x+w,y+h),(0,255,),3) #給識(shí)別對(duì)象寫(xiě)上標(biāo)號(hào) font=cv2.FONT_HERSHEY_SIMPLEX cv2.putText(Img,str(p),(x-10,y+10), font, 1,(0,0,255),2)#加減10是調(diào)整字符位置 p +=1 print '黃色方塊的數(shù)量是',p,'個(gè)'#終端輸出目標(biāo)數(shù)量 cv2.imshow('target', target) cv2.imshow('Mask', mask) cv2.imshow("prod", dilation) cv2.imshow('Img', Img) cv2.imwrite('Img.png', Img)#將畫(huà)上矩形的圖形保存到當(dāng)前目錄 while True: Key = chr(cv2.waitKey(15) & 255) if Key == 'q': cv2.destroyAllWindows() break
原始圖像
處理之后保存的圖像
聯(lián)系客服