python - 我想替换图像中所有不是黑色文本和白色背景的东西
问题描述
我试过这样做,但运行时间太长。问题是图像中的黑色文本是由许多不同的灰度和颜色组成的。我还想删除 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)
解决方案
如果您正在寻找性能,我会尽可能多地避免使用for
语句,因为它们python
比其他低级语言(如C
or 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
的!
希望能帮助到你!
推荐阅读
- sql - 如何在sql server中获取当前年份完整月份列表和往年完整月份列表?
- c# - 某些类的 ctor 中的常见接口用法
- javascript - 在服务器上记录客户端 JavaScript 错误
- c# - 如何解决 Visual Studio 中的 NuGet 错误
- c# - 使用实体框架(代码优先方法)我只能从列表中插入 63 条记录中的一条?
- typescript - 如何为 WebStorm 和 VSCode 设置相同的代码格式样式?
- python - 组合两个数据框时保留索引
- android - 确定 Google Play 一次性产品是否有效 (IAB)
- ios - 高阶函数 sort() 将它与其他高阶函数一起使用,它也与 let 内容一起使用
- scala - 如何在 Spark Standalone 集群中提交多个作业?