python opencv檢測並提取目標顏色

來源:互聯網
上載者:User
這次給大家帶來python opencv檢測並提取目標顏色,python opencv檢測並提取目標顏色的注意事項有哪些,下面就是實戰案例,一起來看一下。

執行個體如下所示:

# -*- 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映像轉換為HSV格式  '''  HSV模型中顏色的參數分別是:色調(H),飽和度(S),明度(V)  下面兩個值是要識別的色彩範圍  '''  Lower = np.array([20, 20, 20])#要識別顏色的下限  Upper = np.array([30, 255, 255])#要識別的顏色的上限  #mask是把HSV圖片中在色彩範圍內的地區變成白色,其他地區變成黑色  mask = cv2.inRange(HSV, Lower, Upper)  #下面四行是用卷積進行濾波  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是把原圖中的非目標顏色地區去掉剩下的映像  target = cv2.bitwise_and(Img, Img, mask=dilation)  #將濾波後的映像變成二值映像放在binary中  ret, binary = cv2.threshold(dilation,127,255,cv2.THRESH_BINARY)   #在binary中發現輪廓,輪廓按照面積從小到大排列  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)#將輪廓分解為識別對象的左上方座標和寬、高   #在映像上畫上矩形(圖片、左上方座標、右下角座標、顏色、線條寬度)   cv2.rectangle(Img,(x,y),(x+w,y+h),(0,255,),3)   #給識別對象寫上標號   font=cv2.FONT_HERSHEY_SIMPLEX   cv2.putText(Img,str(p),(x-10,y+10), font, 1,(0,0,255),2)#加減10是調整字元位置   p +=1  print '黃色方塊的數量是',p,'個'#終端輸出目標數量  cv2.imshow('target', target)  cv2.imshow('Mask', mask)  cv2.imshow("prod", dilation)  cv2.imshow('Img', Img)  cv2.imwrite('Img.png', Img)#將畫上矩形的圖形儲存到目前的目錄   while True:  Key = chr(cv2.waitKey(15) & 255)  if Key == 'q':   cv2.destroyAllWindows()   break

原始映像

處理之後儲存的映像

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

python批量讀取圖片且存入資料庫的實現

在Window10中Python3.5怎麼安裝opencv

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.