bg.jpg
tb.png
結(jié)果.png
以上是需要是別的圖片缺口,來自某東登錄豹悬。
opencv是計(jì)算機(jī)視覺桐筏。
一、cv函數(shù)
1骄恶、imread
:讀取圖片
?imread(image_path, flag)
:
? ? images_path
:圖片路徑食铐,找不到不報(bào)錯(cuò)
?? flag
:
????1/cv2.IMREAD_COLOR
:彩色圖片,圖片透明性會被忽略,默認(rèn)參數(shù)
????0/cv2.IMREAD_GRAYSCALE
:灰色圖片
????-1/cv2.IMREAD_UNCHANGED
:包括其alpha通道
2、imwrite
?imwrite(img_path_name,img)
?? img_path_name
:保存的文件名
??img
:文件對象
3僧鲁、cvtColor
??cvtColor(img,code)
?img
: 圖像對象
?? code
:
??? cv2.COLOR_RGB2GRAY
: RGB轉(zhuǎn)換到灰度模式
???cv2.COLOR_RGB2HSV
: RGB轉(zhuǎn)換到HSV模式(hue,saturation,Value)
4虐呻、matchTemplate
?matchTemplate(img_path, bg_path, cv2.TM_CCOEFF_NORMED)
??img_path
:對比圖片
??bg_path
:背景圖片
??cv2.TM_CCOEFF_NORMED
以下源碼
# encoding=utf8
import cv2
import numpy as np
def show(name):
cv2.imshow('Show', name)
cv2.waitKey(0)
cv2.destroyAllWindows()
def main():
otemp = './images/tb.png'
oblk = './images/bg.jpg'
target = cv2.imread(otemp, 0)
template = cv2.imread(oblk, 0) # 讀取到兩個(gè)圖片,進(jìn)行灰值化處理
w, h = target.shape[::-1]
print(w, h)
temp = './images/temp.jpg'
targ = './images/targ.jpg'
cv2.imwrite(temp, template)
cv2.imwrite(targ, target) # 處理后進(jìn)行保存
target = cv2.imread(targ)
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY) # 轉(zhuǎn)化到灰度
target = abs(255 - target) # 返回絕對值
cv2.imwrite(targ, target) # 重新寫入
target = cv2.imread(targ)
template = cv2.imread(temp)
result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED) #進(jìn)行匹配
x, y = np.unravel_index(result.argmax(), result.shape) # 通過np轉(zhuǎn)化為數(shù)值寞秃,就是坐標(biāo)
# 展示圈出來的區(qū)域
cv2.rectangle(template, (y, x), (y + w, x + h), (7, 249, 151), 2)
show(template)
return y, x
if __name__ == '__main__':
main()
優(yōu)化代碼
import cv2
import numpy as np
def from_file_get_distanct(hx, bg):
'''
根據(jù)文件進(jìn)行識別
:param hx: 滑塊圖片的文件路徑
:param bg: 背景圖片的文件路徑
:return:
'''
target = cv2.imread(hx)
template = cv2.imread(bg, 0) # 讀取到兩個(gè)圖片斟叼,進(jìn)行灰值化處理
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY) # 轉(zhuǎn)化到灰度
target = abs(255 - target) # 返回絕對值
target = cv2.cvtColor(target, cv2.COLOR_GRAY2RGB) # 單通道轉(zhuǎn)3通道
template = cv2.cvtColor(template, cv2.COLOR_GRAY2RGB)
result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED) # 進(jìn)行匹配
x, y = np.unravel_index(result.argmax(), result.shape) # 通過np轉(zhuǎn)化為數(shù)值,就是坐標(biāo)
return y, x
def from_buffer_get_distanct(hx, bg):
'''
根據(jù)二進(jìn)制進(jìn)行識別
:param hx: 滑塊圖片的二進(jìn)制
:param bg: 背景圖片的二進(jìn)制
:return:
'''
target = cv2.imdecode(np.frombuffer(hx, np.uint8), cv2.IMREAD_COLOR)
template = cv2.imdecode(np.frombuffer(bg, np.uint8), cv2.IMREAD_COLOR) if type(bg) == bytes else cv2.cvtColor(
np.asarray(bg), cv2.COLOR_RGB2BGR) # 如果是PIL.images就換讀取方式
target = cv2.cvtColor(target, cv2.COLOR_BGR2GRAY) # 轉(zhuǎn)化到灰度
target = abs(255 - target) # 返回絕對值
target = cv2.cvtColor(target, cv2.COLOR_GRAY2RGB) # 單通道轉(zhuǎn)3通道
result = cv2.matchTemplate(target, template, cv2.TM_CCOEFF_NORMED) # 進(jìn)行匹配
x, y = np.unravel_index(result.argmax(), result.shape) # 通過np轉(zhuǎn)化為數(shù)值春寿,就是坐標(biāo)
return y, x