【问题标题】:Trouble creating PIL Image object from canvas tag with Selenium使用 Selenium 从画布标签创建 PIL Image 对象时遇到问题
【发布时间】:2016-06-22 00:45:31
【问题描述】:

我正在尝试基于使用 Selenium 从 this 网站提取的 canvas 标签创建 PIL Image 对象。目标是使用pytesseract 并获取验证码内容。我的代码没有引发任何错误,但创建的图像全是黑色的。

到目前为止我的代码:

# Run JS code to get data URI
png_url = driver.execute_script(
        'return document.getElementsByTagName("canvas")[0].toDataURL("image/png");')
# Parse the URI to get only the base64 part
str_base64 = re.search(r'base64,(.*)', png_url).group(1)
# Convert it to binary
str_decoded = str_base64.decode('base64')
# Create and show Image object
image = Image.open(StringIO(str_decoded))
image.show()    
# Read image with pytesseract
recaptcha = pytesseract.image_to_string(image)

我不知道为什么图像全黑。我的代码基于this 教程,它保存了图像。我不想保存图像,我希望它只在内存中。

编辑:

我已将图像保存在文件系统中,图像保存正常,但背景透明,因此显示时显示为黑色。如何让背景变白?

【问题讨论】:

    标签: python selenium selenium-webdriver python-imaging-library pillow


    【解决方案1】:

    我需要做的就是在this 答案后面提取背景:

    def remove_transparency(im, bg_colour=(255, 255, 255)):
    
        # Only process if image has transparency (https://stackoverflow.com/a/1963146)
        if im.mode in ('RGBA', 'LA') or (im.mode == 'P' and 'transparency' in im.info):
    
            # Need to convert to RGBA if LA format due to a bug in PIL (https://stackoverflow.com/a/1963146)
            alpha = im.convert('RGBA').split()[-1]
    
            # Create a new background image of our matt color.
            # Must be RGBA because paste requires both images have the same format
            # (https://stackoverflow.com/a/8720632  and  https://stackoverflow.com/a/9459208)
            bg = Image.new("RGBA", im.size, bg_colour + (255,))
            bg.paste(im, mask=alpha)
            return bg
    
        else:
            return im
    

    那么完整的代码:

    png_url = driver.execute_script(
                'return document.getElementsByTagName("canvas")[0].toDataURL("image/png");')
    str_base64 = re.search(r'base64,(.*)', png_url).group(1)
    # Convert it to binary
    str_decoded = str_base64.decode('base64')
    image = Image.open(StringIO(str_decoded))
    image = remove_transparency(image)
    recaptcha = pytesseract.image_to_string(image).replace(" ", "")
    

    【讨论】:

      【解决方案2】:

      您应该创建一个 RGB 白色图像并将您的 RGBA 图像粘贴到其中。解决方案可能是this,但也有其他方法。我建议使用 numpy 和 opencv。

      【讨论】:

        猜你喜欢
        • 2014-08-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-08
        相关资源
        最近更新 更多