首页 > 解决方案 > 我想替换图像中所有不是黑色文本和白色背景的东西

问题描述

我试过这样做,但运行时间太长。问题是图像中的黑色文本是由许多不同的灰度和颜色组成的。我还想删除 230 到 255 之间的灰色阴影。我怎样才能做得更好?

OLD_PATH = r'C:\Users\avivb\Desktop\Untitled.png'
NEW_PATH = r'C:\Users\avivb\Desktop\test.png'

R_OLD, G_OLD, B_OLD = (range(230,255), range(230,255), range(230,255))
R_NEW, G_NEW, B_NEW = (255, 255, 255)


from PIL import Image
im = Image.open(OLD_PATH)
pixels = im.load()

width, height = im.size
for x in range(width):
    for y in range(height):
        r, g, b = pixels[x, y]
        for i in R_OLD:
            for j in G_OLD:
                for k in B_OLD:
                    if (r, g, b) == (i, j, k):
                        pixels[x, y] = (R_NEW, G_NEW, B_NEW)
im.save(NEW_PATH)

标签: python

解决方案


如果您正在寻找性能,我会尽可能多地避免使用for语句,因为它们python比其他低级语言(如Cor C++)要慢。

这是我使用的方法openCV,应该非常快:

import cv2 as cv
# Set range of color values
lower = np.array([230, 230, 230])
upper = np.array([255, 255, 255])
# Threshold the image to get only selected colors
mask = cv.inRange(img, lower, upper)
# Set the new value to the masked image
img[mask.astype(bool)] = 255

请注意,这段代码中没有明确for的!

希望能帮助到你!


推荐阅读