Skip to main content

图片相关

cv2图片中文路径

img_path = r'xxxx.png'

# 这里不支持中文路径
img = cv2.imread(img_path)

# 这里就支持中文路径
img = cv2.imdecode(fromfile(img_path, dtype=uint8), -1)

模板匹配

提取自: smart_onmyoji/moduleGetPos.py

def template_matching(img_src, template, screen_width, screen_height, val, debug_status, i):
"""获取坐标"""
# img_src = cv2.cvtColor(img_src, cv2.COLOR_BGR2GRAY)
# template = cv2.cvtColor(template, cv2.COLOR_BGR2GRAY)
if (img_src is not None) and (template is not None):
img_tmp_height = template.shape[0]
img_tmp_width = template.shape[1] # 获取模板图片的高和宽
img_src_height = img_src.shape[0]
img_src_width = img_src.shape[1] # 匹配原图的宽高
res = cv2.matchTemplate(img_src, template, cv2.TM_CCOEFF_NORMED)
min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res) # 最小匹配度,最大匹配度,最小匹配度的坐标,最大匹配度的坐标
if debug_status:
print(f" 第 [ {i+1} ] 张图片,匹配分数:[ {round(max_val,2)} ]")
if max_val >= val: # 计算相对坐标
position = [int(screen_width / img_src_width * (max_loc[0] + img_tmp_width / 2)),
int(screen_height / img_src_height * (max_loc[1] + img_tmp_height / 2))]
return position
else:
return None