【问题标题】:Remove color from an image从图像中去除颜色
【发布时间】:2020-04-11 04:09:28
【问题描述】:

我想从下面的图像中删除颜色,由于这种颜色,我无法从图像中清晰地提取文本。

我正在使用下面的代码,但我没有得到明文,

import numpy as np
from PIL import Image

im = Image.open('my_file.tif')
im = im.convert('RGBA')
data = np.array(im)
# just use the rgb values for comparison
rgb = data[:,:,:3]
color = [246, 213, 139]   # Original value
black = [0,0,0, 255]
white = [255,255,255,255]
mask = np.all(rgb == color, axis = -1)
# change all pixels that match color to white
data[mask] = white

# change all pixels that don't match color to black
##data[np.logical_not(mask)] = black
new_im = Image.fromarray(data)
new_im.save('new_file.tif')

def black_and_white(input_image_path,
                output_image_path):
color_image = Image.open(input_image_path)
bw = color_image.convert('L')
bw.save(output_image_path)

请帮帮我...

图 2:

【问题讨论】:

  • 使用 opencv 以无色模式加载它,然后甚至可能反转它?
  • “我没有得到明文” - 你得到的是什么?预期的输出是多少?
  • 就像@ForceBru 说的,请提供您当前的输入和输出。
  • 你的问题很模糊。您要去除哪种颜色 - 至少有 3 种蓝色以及白色和灰色?当您去除颜色时,您期望会留下什么?黑色的?白色的?灰色的?透明度?
  • 我想删除该图像中的所有颜色,除了文本颜色

标签: python image opencv image-processing python-imaging-library


【解决方案1】:

我假设您想提取报价。为此,您可以执行一系列过滤操作来去除非文本轮廓。处理完结果后,您可以使用诸如 Pytesseract 之类的 OCR 工具进行文本提取。

OCR 的结果

On behalf of the hundreds of ACLU activists who
called on Governor Walker to veto House Bill
156, we are disappointed that he did not put
students or the Constitution first today.”
—Joshua A. Decker
Executive Director

代码

import cv2
import pytesseract

pytesseract.pytesseract.tesseract_cmd = r"C:\Program Files\Tesseract-OCR\tesseract.exe"

# Load image and threshold
image = cv2.imread('1.png')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
thresh = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)[1]

# Connect text with a horizontal shaped kernel
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (10,3))
dilate = cv2.dilate(thresh, kernel, iterations=3)

# Remove non-text contours using aspect ratio filtering
cnts = cv2.findContours(dilate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
cnts = cnts[0] if len(cnts) == 2 else cnts[1]
for c in cnts:
    x,y,w,h = cv2.boundingRect(c)
    aspect = w/h
    if aspect < 3:
        cv2.drawContours(thresh, [c], -1, (0,0,0), -1)

# Invert image and OCR
result = 255 - thresh
data = pytesseract.image_to_string(result, lang='eng',config='--psm 6')
print(data)

cv2.imshow('result', result)
cv2.waitKey()

【讨论】:

  • 您的答案适用于这张图片。但是对于另一个图像,它不起作用。扩张后,整个数据将消失,最终的图像结果什么都没有(全白)。我将该图像添加到我的问题中。请检查并提出动态解决方案。
  • 它可能不适用于文本在背景颜色之上具有不同颜色阴影的图像
  • 有什么方法可以从这些图像中提取数据。否则,请提出一些想法来提高这些图像的 OCR 准确性。
  • 是的,它可能,但解决方案不会是动态的,它适用于每个特定情况。使用传统图像处理技术获得适用于所有情况的动态解决方案很困难
  • 您能解释一下如何以通用方法处理该图像吗?这对我真的很有帮助。
【解决方案2】:

尝试OpenCV转换,但记得使用3个通道,否则会报错

gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

【讨论】:

    猜你喜欢
    • 2013-04-28
    • 2021-10-01
    • 2013-09-07
    • 2018-10-21
    • 2019-01-13
    • 1970-01-01
    • 1970-01-01
    • 2020-01-05
    • 2011-07-27
    相关资源
    最近更新 更多