【发布时间】:2018-06-14 04:36:37
【问题描述】:
我正在尝试使用 OpenCV 和 selenium 将 html 中的特定元素保存为图像文件。但无法保存文件。
from selenium import webdriver
import cv2
import numpy as np
browser = webdriver.Firefox()
browser.get(<URl with image>)
# Element to be saved
element = browser.find_element_by_id(<id of element>)
png = browser.get_screenshot_as_png()
location = element.location
size = element.size
nparr = np.frombuffer(png, np.uint8)
img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
left = location['x']
top = location['y']
right = location['x'] + size['width']
bottom = location['y'] + size['height']
im = img[left:right, top:bottom]
cv2.imwrite('filename.png',im)
目前'filename.png'中没有图片数据通过运行这个脚本。
【问题讨论】:
-
能否调试
left、top、right和bottom中存储的值 -
>>>print (left, top, right, bottom) >>>755 405 987.0 482.0 -
将
right和bottom转换为整数会更好。你也可以调试print img.shape吗?这里要注意的一件事是您以错误的方式裁剪imgnumpy 矩阵,正确的做法是im= img[top:bottom, left:right] -
感谢您解决了问题。
标签: python selenium numpy opencv crop