Ujw*_*til 5 python pixel image-processing python-imaging-library
我想自定义图像颜色以制作具有颜色变体的类似图像。
例子 :
对于上面的图像,我想用其他颜色替换红色,例如蓝色,绿色,黄色,黑色等。
我试过 :
from PIL import Image
filename ="./Logo.jpg"
picture = Image.open(filename, 'r')
_colors = [(255, 255, 255), (128, 128, 0), (128, 128, 128), (192, 128, 0), (128, 64, 0), (0, 192, 0), (128, 64, 128), (255, 255, 255)]
width, height = picture.size
for x in range(0, width):
for y in range(0, height):
current_color = picture.getpixel((x,y))
# print (current_color)
if current_color in _colors:
picture.putpixel((x,y), (255,5, 255))
# print ("Y")
picture.save("./test/change.png")
Run Code Online (Sandbox Code Playgroud)
上面的代码是非常常见的代码,建议大多数人使用。但这是相当困难的,因为它替换了列表“ _colors ”中的像素输出图像是:
上述问题有什么解决办法吗?有什么聪明的方法可以使用机器学习来处理这个问题吗?有使用其他编程语言的解决方案吗?
我对PIL不熟悉,听说它很慢。这是 OpenCV 版本:
# for red color, it's easier to work with negative image
# since hue is in [170, 180] or [0,10]
hsv_inv = cv2.cvtColor(255-img, cv2.COLOR_BGR2HSV)
# these are cyan limit, but we're working on negative image, so...
lower_range = np.array([80,0,0])
upper_range = np.array([100,255,255])
# mask the red
mask = cv2.inRange(hsv_inv, lower_range, upper_range)
# replace red by green
green_hsv = hsv_inv.copy()
green_hsv[np.where(mask)] += np.array([60,0,0], dtype=np.uint8)
green_img = 255 - cv2.cvtColor(green_hsv, cv2.COLOR_HSV2BGR)
purple_hsv = hsv_inv.copy()
purple_hsv[np.where(mask)] -= np.array([30,0,0], dtype=np.uint8)
purple_img = 255 - cv2.cvtColor(purple_hsv, cv2.COLOR_HSV2BGR)
Run Code Online (Sandbox Code Playgroud)
结果,请忽略我通过 matplotlib 展示的刻度。