資源簡介
opencv 利用攝像頭來判斷石頭剪刀布的小游戲,代碼值得一看。
代碼片段和文件信息
import?cv2
import?numpy
import?time
import?random
import?os
def?judge():
????#?構造一個3×3的結構元素
????#?return?0?stone?1?jiandao?2?bu
????img?=?cv2.imread(“wif.jpg“?0)
????element?=?cv2.getStructuringElement(cv2.MORPH_RECT?(11?11))#矩形:MORPH_RECT??交叉形:MORPH_CROSS??橢圓形:MORPH_ELLIPSE
????dilate?=?cv2.dilate(img?element)
????erode?=?cv2.erode(img?element)
????#?將兩幅圖像相減獲得邊,第一個參數是膨脹后的圖像,第二個參數是腐蝕后的圖像
????result?=?cv2.absdiff(dilate?erode);
????#?上面得到的結果是灰度圖,將其二值化以便更清楚的觀察結果
????retval?result?=?cv2.threshold(result?40?255?cv2.THRESH_BINARY);
????#?反色,即對二值圖每個像素取反
????result?=?cv2.bitwise_not(result);
????“““
python-opencv圖像的位操作:圖像與運算cv2.bitwise_and,圖像或運算cv2.bitwise_or,圖像非運算cv2.bitwise_not與圖像異或運算cv2.bitwise_xor。
1)圖像與運算-cv2.bitwise_and(src1?src2?dst=None?mask?=?None)
2)圖像或運算-cv2.bitwise_or(src1?src2?dst=None?mask?=?None)
3)圖像非運算-cv2.bitwise_not(src1?src2?dst=None?mask?=?None)
圖像非運算的效果:一個二值圖,將黑色轉為白色,白色轉為黑色。
????“““
????result?=?cv2.medianBlur(result?23)
????#cv2.imshow(“test“result)
????“““
這里介紹非線性過濾器——中值濾波器。
由于中值濾波器對消除椒鹽現象特別有用。所以我們使用第二篇教程中椒鹽函數先對圖像進行處理,將處理結果作為示例圖片。
調用中值濾波器的方法與調用其他濾波器的方法類似,如下:
result?=?cv2.medianBlur(image5)??
函數返回處理結果,第一個參數是待處理圖像,
第二個參數是孔徑的尺寸,一個大于1的奇數。
比如這里是5,中值濾波器就會使用5×5的范圍來計算。即對像素的中心值及其5×5鄰域組成了一個數值集,對其進行處理計算,當前像素被其中值替換掉。
????“““
????a?=?[]
????posi?=?[]
????width?=?[]
????count?=?0
????area?=?0
????#這個大神的計算方法,我一時也解析不出來,應該是依靠手勢面積來計算的
????for?i?in?range(result.shape[1]):
????????for?j?in?range(result.shape[0]):
????????????if?(result[j][i]?==?0):
????????????????area?+=?1
????for?i?in?range(result.shape[1]):
????????if?(result[5?*?result.shape[0]?//?16][i]?==?0?and?result[5?*?result.shape[0]?//?16][i?-?1]?!=?0):
????????????count?+=?1
????????????width.append(0)
????????????posi.append(i)
????????if?(result[5?*?result.shape[0]?//?16][i]?==?0):
????????????width[count-1]+=?1????#?如果在這里報錯,是因為背景問題,請讓手的背景盡量整潔
????#這里是調試用的代碼可以注釋掉
????print?(‘the?pic?width?is?‘result.shape[1]‘\n‘)
????for?i?in?range(count):
????????print?(‘the?‘i‘th‘‘?‘‘is‘)
????????print?(‘width?‘width[i]?)
????????print?(‘posi?‘posi[i]‘\n‘)
????print?(count‘\n‘)
????print?(‘area?is?‘area‘\n‘)
????cv2.line(result(05*result.shape[0]//16)(2145*result.shape[0]//16)(000))
????cv2.namedWindow(“test“)
????cv2.imshow(“test“result)
????cv2.waitKey(0)
????#這里是調試用的代碼可以注釋掉
????#?判定時間
????width_length?=?0
????width_jiandao?=?True
????for?i?in?range(count):
????????if?width[i]?>?45:
????????????#?print?‘bu1‘;
????????????return?2;
????????if?width[i]?<=?20?or?width[i]?>=?40:
????????????width_jiandao?=?False
????????width_length?+=?width[i]
????if?width_jiandao?==?True?and?count?==?2:
????????return?1;
????if?(area?8500):
????????print?(‘shi?tou‘)
????????return?0;
????print(“width_leng“?width_length)
????if?(width_length?35):
????????#?這個時候說明照片是偏下的,所以需要重新測定。
????????a?=?[]
評論
共有 條評論