更改RGB图像的颜色

问题描述 投票:-3回答:3

我有一个图像(我同时以NumPy和PIL格式都有它,我想将RGB值从[0.4, 0.4, 0.4]更改为[0.54, 0.27, 0.07]

通过这样做,我想将道路颜色从灰色更改为棕色:

“路”

python numpy colors python-imaging-library rgb
3个回答
1
投票

您可以尝试这种numpy方法:

img[np.where(img == (0.4,0.4,0.4))] = (0.54,0.27,0.27)

0
投票

已加载的图像表示为三维数组。它的形状应为height, width, color channel。就是如果仅具有RGB通道(某些通道可能具有RGBA等),则矩阵属性看起来像height, width, 3

其余部分应该与对待普通数组一样。您可以这样查看:

pixel = image[height][width][colorchannel]

Quang Hoang的答案为您解决了简单的问题。


0
投票

我必须就proposed solution by Quang Hong与Majid Shirazi达成共识。让我们看一下:

idx = np.where(img == (0.4, 0.4, 0.4))

然后,idx是一个三元组,其中包含所有ndarray坐标,x坐标和“通道”坐标的y。从NumPy的indexing中,我看不到使用建议的命令以期望的方式正确访问/操作img中的值的可能性。我宁愿重现评论中指出的确切错误。

为了获得适当的integer array indexing,需要提取x-和y坐标。以下代码将显示该内容。或者,也可以使用boolean array indexing。我将其添加为附件:

import cv2
import numpy as np

# Some artificial image
img = np.swapaxes(np.tile(np.linspace(0, 1, 201), 603).reshape((201, 3, 201)), 1, 2)
cv2.imshow('before', img)

# Proposed solution
img1 = img.copy()
idx = np.where(img1 == (0.4, 0.4, 0.4))
try:
    img1[idx] = (0.54, 0.27, 0.27)
except ValueError as e:
    print(e)

# Corrected solution for proper integer array indexing: Extract x and y coordinates
img1[idx[0], idx[1]] = (0.54, 0.27, 0.27)
cv2.imshow('after: corrected solution', img1)

# Alternative solution using boolean array indexing
img2 = img.copy()
img2[np.all(img2 == (0.4, 0.4, 0.4), axis=2), :] = (0.54, 0.27, 0.27)
cv2.imshow('after: alternative solution', img2)

cv2.waitKey(0)
cv2.destroyAllWindows()

希望有帮助并明确说明!

© www.soinside.com 2019 - 2024. All rights reserved.