如何使用Python识别网页指定图像?CV2模板匹配位置偏差求解
问题说明
我开发了一款简单的Python应用,使用CV2计算机视觉库识别网页中的模板图像。
我为该应用传入需要在源图像中识别的模板图像。本次案例中,源图像是网站www.google.com的截图,模板图像是谷歌搜索按钮。
模板图像

一开始我以为应用运行正常,但它在输入(源)图像上绘制的矩形位置完全错误。我在下方附上了应用定位到模板图像位置的结果图。
结果图

以下是源代码:
主应用源码
import cv2 import numpy from io import BytesIO from PIL import Image import matplotlib.pyplot as plt import numpy as np class Automate: def __init__(self): chrome_options = Options() chrome_options.add_argument("kiosk") self.driver = webdriver.Chrome(ChromeDriverManager("93.0.4577.63").install(), options=chrome_options) #self.driver = webdriver.Chrome(executable_path='./chromedriver',options=chrome_options) self.screenShot = None self.finalImage = None def open_webpage(self, url): print(f"Open webpage {url}") self.driver.get(url) def close_webpage(self): Event().wait(5) self.driver.close() print("Closing webpage") def snap_screen(self): print("Capturing screen") self.screenShot = "screenshot.png" self.driver.save_screenshot(self.screenShot) print("done.") def match(self, image, template): # convert images to greyscale. src = cv2.cvtColor(cv2.imread(image), cv2.COLOR_BGR2GRAY) temp = cv2.cvtColor(cv2.imread(template), cv2.COLOR_BGR2GRAY) cv2.imshow("out", temp) cv2.waitKey(0) height, width = src.shape H, W = temp.shape result = cv2.matchTemplate(src, temp, cv2.cv2.TM_CCOEFF_NORMED) minVal, maxVal, minLoc, maxLoc = cv2.minMaxLoc(result) location = maxLoc bottomRight = (location[0] + W, location[1] + H) src2 = cv2.imread(image) cv2.rectangle(src2, location, bottomRight, (0, 0, 255), 5) cv2.imshow("output", src2) cv2.waitKey(0) cv2.destroyAllWindows() def main(): url = "http://www.google.com" auto = Automate() auto.open_webpage(url) auto.snap_screen() auto.close_webpage() match_image = "images/templates/google-button.png" # Match screenshot with template image. auto.check_match( image=auto.screenShot, template=match_image )
恳请各位提供解决该问题的帮助或建议,非常感谢。
后续更新
采纳用户zteffi的建议后,我将模板图像调整到了正确的尺寸,调整后模板匹配功能可正常运行。
需要确保模板图像的尺寸尽可能接近源图像中待识别目标的实际尺寸。在本案例中,模板尺寸设置为150×150或200×200左右时更容易识别到目标按钮。
内容的提问来源于stack exchange,提问作者Chesneycar
相关产品推荐
相关产品推荐

