Python?OpenCV實(shí)現(xiàn)簡(jiǎn)單的顏色識(shí)別功能(對(duì)紅色和藍(lán)色識(shí)別并輸出)
攝像頭識(shí)別紅色和藍(lán)色并框選,當(dāng)該顏色為攝像頭屏幕上大多數(shù)顏色時(shí)打印出該顏色的名稱
1.調(diào)包
import cv2 import numpy as np from matplotlib import pyplot as plt
2.初始設(shè)置
lower_red = np.array([0, 50, 100]) #為紅色和藍(lán)色設(shè)置閾值用來為之后處理圖像準(zhǔn)備
upper_red = np.array([10, 255, 255]) #該閾值是在HSV顏色空間下
lower_blue = np.array([100,50,100])
upper_blue = np.array([124, 255, 255])
red = (0,0,225) #設(shè)置紅色和藍(lán)色在BGR顏色空間下的數(shù)值元組
blue = (225,0,0)
cv2.namedWindow('video', cv2.WINDOW_AUTOSIZE)#設(shè)置窗口'video',大小為自適應(yīng)模式
cv2.resizeWindow('video',640,480) #為窗口設(shè)置寬度(640)和高度(480)3.圖像處理,提取顏色
def img_process(img,lower,upper):
"""根據(jù)閾值處理圖像,提取閾值內(nèi)的顏色。返回處理后只留下指定顏色的圖像(其余為黑色)
img:原圖像;lower:最低閾值;upper:最高閾值"""
kernel = np.ones((35, 35), np.uint8) #創(chuàng)建一個(gè)35x35卷積核,卷積核內(nèi)元素全為1
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #將BGR圖像轉(zhuǎn)化為HSV圖像,方便顏色提取
Open = cv2.morphologyEx(hsv,cv2.MORPH_OPEN,kernel) #用卷積核對(duì)圖像進(jìn)行形態(tài)學(xué)開運(yùn)算操作,去除噪聲
mask = cv2.inRange(Open, lower, upper) #開運(yùn)算得到的圖像用閾值進(jìn)行二值化處理(處理后的結(jié)果為在閾值內(nèi)的部分變?yōu)榘咨?,不在閾值?nèi)的部分為黑色)
res = cv2.bitwise_and(img, img, mask = mask) #二值化處理后的圖像與原圖進(jìn)行位與運(yùn)算(處理后在閾值內(nèi)的顏色變?yōu)樵伾?,不在閾值?nèi)的部分仍為黑色)
return res #該函數(shù)的返回值為位與運(yùn)算之后的圖像,此圖像只保留了在閾值內(nèi)的圖像,其余部分為黑色4.輪廓繪制
def cnts_draw(img,res,color):
"""在原圖像上繪出指定顏色的輪廓。無返回值
img:原圖像;res:只剩某顏色的位與運(yùn)算后的圖像;color:輪廓的顏色"""
canny = cv2.Canny(res,100,200)#Canny邊緣檢測(cè)算法,用來描繪圖像中物體的邊緣,(100,200為此函數(shù)的兩個(gè)閾值,該閾值越小輪廓的細(xì)節(jié)越豐富)
contours, hierarchy=cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)#尋找圖像輪廓的函數(shù),這里先用Canny算法得到只保留輪廓的圖像方便輪廓的找尋
if len(contours) == 0:#傳遞到max函數(shù)中的輪廓不能為空
cv2.imshow('video',img)
return
else:
max_cnt = max(contours , key = cv2.contourArea)#找到輪廓中最大的一個(gè)
cv2.drawContours(img, max_cnt,-1,color,2)#在原圖上繪制這個(gè)最大輪廓
(x,y,w,h) = cv2.boundingRect(max_cnt)#找到這個(gè)最大輪廓的最大外接矩形,返回的(x,y)為這個(gè)矩形右下角的頂點(diǎn),w為寬度,h為高度
cv2.rectangle(img,(x,y),(x+w,y+h),color,3)#在原圖上繪制這個(gè)矩形
cv2.imshow('video', img)#展示原圖5.顏色識(shí)別
def colorfind(img):
"""找到原圖像最多的顏色,當(dāng)該顏色為紅色或藍(lán)色時(shí)打印出來該顏色的名稱,無返回值
img:原圖像"""
kernel = np.ones((35, 35), np.uint8)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Open = cv2.morphologyEx(hsv,cv2.MORPH_OPEN,kernel)#以上為圖像處理
hist = cv2.calcHist([Open],[0],None,[180],[0,180])#對(duì)Open圖像的H通道進(jìn)行直方圖統(tǒng)計(jì)
hist_max = np.where(hist == np.max(hist))#找到直方圖hist中列方向最大的點(diǎn)hist_max
if 0 < hist_max[0] < 10:#hist_max[0]為hist_max的行方向的值,即H的值,H在0~10為紅色
print('red')
elif 100 < hist_max[0] < 124:#H在100~124為藍(lán)色
print('blue')
else : #H不在前兩者之間跳出函數(shù)
return
#可以添加對(duì)H的判斷來識(shí)別更多的顏色下面是OpenCV中HSV空間顏色對(duì)照表

6.程序主體
if __name__ == "__main__":
cap = cv2.VideoCapture(0)#打開攝像頭(0代表打開默認(rèn)攝像頭,若有兩個(gè)攝像頭可用1表示打開另一個(gè)攝像頭)
while cap.isOpened():#判斷攝像頭是否正常打開
flag, frame = cap.read()#讀取攝像頭返回兩個(gè)參數(shù),flag是布爾類型代表攝像頭是否正常讀取,frame是從攝像頭讀取的圖像
if not flag: #若無法讀取則跳出循環(huán)
print("無法讀取攝像頭!")
break
else:
if frame is not None: #判斷攝像頭有無畫面
res_blue = img_process(frame,lower_blue,upper_blue)
res_red = img_process(frame,lower_red,upper_red)
cnts_draw(frame,res_blue,blue)
cnts_draw(frame,res_red,red)
colorfind(frame)
key = cv2.waitKey(10)
if key == 27:
break
else:
print("無畫面")
break
cap.release()#釋放資源,停止讀取攝像頭
cv2.destroyAllWindows()#關(guān)閉所有窗口完整源代碼
import cv2
import numpy as np
from matplotlib import pyplot as plt
lower_red = np.array([0, 50, 100])
upper_red = np.array([10, 255, 255])
lower_blue = np.array([100,50,100])
upper_blue = np.array([124, 255, 255]) #若繪制輪廓與自己期望的識(shí)別結(jié)果相差較大,可通過調(diào)整閾值來改變識(shí)別結(jié)果
red = (0,0,225)
blue = (225,0,0)
cv2.namedWindow('video', cv2.WINDOW_AUTOSIZE)
cv2.resizeWindow('video',640,480)
def img_process(img,lower,upper):
"""根據(jù)閾值處理圖像,提取閾值內(nèi)的顏色。返回處理后只留下指定顏色的圖像(其余為黑色)
img:原圖像;lower:最低閾值;upper:最高閾值"""
kernel = np.ones((35, 35), np.uint8)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Open = cv2.morphologyEx(hsv,cv2.MORPH_OPEN,kernel)
mask = cv2.inRange(Open, lower, upper)
res = cv2.bitwise_and(img, img, mask = mask)
return res
def cnts_draw(img,res,color):
"""在原圖像上繪出指定顏色的輪廓。無返回值
img:原圖像;res:只剩某顏色的位與運(yùn)算后的圖像;color:輪廓的顏色"""
canny = cv2.Canny(res,100,200)
contours, hierarchy=cv2.findContours(canny,cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)
if len(contours) == 0:
cv2.imshow('video',img)
return
else:
max_cnt = max(contours , key = cv2.contourArea)
cv2.drawContours(img, max_cnt,-1,color,2)
(x,y,w,h) = cv2.boundingRect(max_cnt)
cv2.rectangle(img,(x,y),(x+w,y+h),color,3)
cv2.imshow('video', img)
def colorfind(img):
"""找到原圖像最多的顏色,當(dāng)該顏色為紅色或藍(lán)色時(shí)打印出來該顏色的名稱,無返回值
img:原圖像"""
kernel = np.ones((35, 35), np.uint8)
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
Open = cv2.morphologyEx(hsv,cv2.MORPH_OPEN,kernel)
hist = cv2.calcHist([Open],[0],None,[180],[0,180])
hist_max = np.where(hist == np.max(hist))
if 0 < hist_max[0] < 10:
print('red')
elif 100 < hist_max[0] < 124:
print('blue')
else :
return
if __name__ == "__main__":
cap = cv2.VideoCapture(0)
while cap.isOpened():
flag, frame = cap.read()
if not flag:
print("無法讀取攝像頭!")
break
else:
if frame is not None:
res_blue = img_process(frame,lower_blue,upper_blue)
res_red = img_process(frame,lower_red,upper_red)
cnts_draw(frame,res_blue,blue)
cnts_draw(frame,res_red,red)
colorfind(frame)
key = cv2.waitKey(10)
if key == 27:
break
else:
print("無畫面")
break
cap.release()
cv2.destroyAllWindows()下面是程序運(yùn)行的實(shí)例


總結(jié)
到此這篇關(guān)于Python OpenCV實(shí)現(xiàn)簡(jiǎn)單的顏色識(shí)別功能的文章就介紹到這了,更多相關(guān)Python OpenCV實(shí)現(xiàn)顏色識(shí)別內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python+OpenCV實(shí)現(xiàn)圖片及視頻中選定區(qū)域顏色識(shí)別
- Python+OpenCV實(shí)現(xiàn)基于顏色的目標(biāo)識(shí)別
- python+opencv實(shí)現(xiàn)文字顏色識(shí)別與標(biāo)定功能
- python實(shí)現(xiàn)簡(jiǎn)單顏色識(shí)別程序
- 50行Python代碼實(shí)現(xiàn)視頻中物體顏色識(shí)別和跟蹤(必須以紅色為例)
- 淺談Python3識(shí)別判斷圖片主要顏色并和顏色庫進(jìn)行對(duì)比的方法
- python微信跳一跳系列之棋子定位顏色識(shí)別
- python識(shí)別圖片中指定顏色的圖案并保存為圖片
相關(guān)文章
如何利用python給微信公眾號(hào)發(fā)消息實(shí)例代碼
使用過微信公眾號(hào)的小伙伴應(yīng)該知道微信公眾號(hào)有時(shí)候會(huì)給你推一些文章,當(dāng)你選擇它的某個(gè)功能時(shí),它還會(huì)返回一些信息,下面這篇文章主要給大家介紹了關(guān)于如何利用python給微信公眾號(hào)發(fā)消息的相關(guān)資料,需要的朋友可以參考下2022-03-03
Flask框架學(xué)習(xí)筆記之使用Flask實(shí)現(xiàn)表單開發(fā)詳解
這篇文章主要介紹了Flask框架學(xué)習(xí)筆記之使用Flask實(shí)現(xiàn)表單開發(fā),結(jié)合實(shí)例形式較為詳細(xì)的分析了flask框架表單模板定義、數(shù)據(jù)提交等相關(guān)操作技巧,需要的朋友可以參考下2019-08-08
python創(chuàng)建只讀屬性對(duì)象的方法(ReadOnlyObject)
有時(shí)需要?jiǎng)?chuàng)建一個(gè)帶只讀屬性的對(duì)象,大家可以參考下如下的方法進(jìn)行創(chuàng)建,稍加改造,可以得到很特殊的效果2013-02-02

