gpt4 book ai didi

python - 如何重新着色图像中的多个像素 - Python

转载 作者:行者123 更新时间:2023-12-02 16:06:51 25 4
gpt4 key购买 nike

我尝试了这个脚本来替换图像的单一颜色。我需要在图像中重新着色相似的颜色。例如,我有蓝色,石板蓝。我想用红色重新着色这两种颜色。但正如我在下面提到的,我不能那样做。它可以在 python 的 PIL 或 OpenCV 库中。

此代码来源:Change specific RGB color pixels to another color, in image file

import numpy as np
from PIL import Image

image = Image.open('wall.jpg')
data = np.array(im)

r1, g1, b1 = 81, 90, 103 # Original value
r2, g2, b2 = 255, 0, 0 # Value that we want to replace it with

red, green, blue = data[:,:,0], data[:,:,1], data[:,:,2]
mask = (red == r1) & (green == g1) & (blue == b1)
data[:,:,:3][mask] = [r2, g2, b2]

im = Image.fromarray(data)
im.show()

最佳答案

根据我对您的“相似颜色”的理解,您需要将蓝色及其变体转换为红色。我会给你一个解决方案来在 OpenCV 中做到这一点。使用 cv2.inRange 在 HSV 颜色空间而不是 RGB 中分割颜色更容易创建颜色在该范围内的位置的掩码。 .

创建掩码后,因为它的值为 255 和 0,我将它除以 255 以将其转换为 1 和 0,然后将其转换为 bool 值。然后就像你在你的问题中展示的那样,无论面具是真的,新颜色都会被放置。编码:

import cv2
import numpy as np

img = cv2.imread('2.jpg')
res = img.copy()
hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

lower_green = np.array([40,50,50])
upper_green = np.array([80,255,255])
r2, g2, b2 = 255, 0, 0

mask = cv2.inRange(hsv, lower_green, upper_green)

mask = mask/255
mask = mask.astype(np.bool)
res[:,:,:3][mask] = [b2, g2, r2] # opencv uses BGR

cv2.imshow('image', img)
cv2.imshow('Result', res)
cv2.waitKey(0)
cv2.destroyAllWindows()

Result

我转换了绿色,因为这张图片中的蓝色非常少。您可以使用 [100, 50, 50]作为您的较低范围和 [130, 255, 255]作为你的上限。

关于python - 如何重新着色图像中的多个像素 - Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62108846/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com