python 如何在多次绘制相同像素值的numpy图像数组时获得相同的颜色

rt4zxlrg  于 2023-05-16  发布在  Python
关注(0)|答案(1)|浏览(184)

我正试图在一系列图像上进行一些像素操作。我遇到了一个问题,当绘制相同的像素值有不同的颜色时,绘制不同范围的像素。
例如,我有一张图像,它有六个不同的像素值(0,2,3,4,5,6):
代码1:

import numpy as np
import matplotlib.pyplot as plt
import cv2

image = np.zeros(shape=[256, 256], dtype=np.uint8)

cv2.circle(image, center=(50, 50), radius=10, color=(2, 2), thickness= -1)
cv2.circle(image, center=(100, 100), radius=10, color=(3, 3), thickness= -1)
cv2.circle(image, center=(150, 150), radius=10, color=(4, 4), thickness= -1)
cv2.circle(image, center=(75, 200), radius=10, color=(5, 5), thickness= -1)
cv2.circle(image, center=(200, 89), radius=10, color=(6, 6), thickness= -1)

plt.imshow(image)
plt.show()

输出:

现在,当我在图像中添加两个具有不同像素值(7,12)的形状时,所有现有像素的颜色都会发生变化
代码2:

image = np.zeros(shape=[256, 256], dtype=np.uint8)

cv2.circle(image, center=(50, 50), radius=10, color=(2, 2), thickness= -1)
cv2.circle(image, center=(100, 100), radius=10, color=(3, 3), thickness= -1)
cv2.circle(image, center=(150, 150), radius=10, color=(4, 4), thickness= -1)
cv2.circle(image, center=(75, 200), radius=10, color=(5, 5), thickness= -1)
cv2.circle(image, center=(200, 89), radius=10, color=(6, 6), thickness= -1)
cv2.circle(image, center=(21, 230), radius=5, color=(7, 7), thickness= -1)
cv2.circle(image, center=(149, 250), radius=5, color=(12, 12), thickness= -1)

plt.imshow(image)
plt.show()

输出:

我怎样才能确保相同的像素值给我相同的颜色,而不管任何其他像素存在与否?

ffx8fchx

ffx8fchx1#

这是由于使用的色彩Map表。Matplotlib根据绘制的值调整色彩Map。如果要确保使用的颜色Map表值/范围相同,请使用最大值和最小值明确指定范围:

# Here adapt and choose the values that suits you the best
min_value = -10
max_value = 10

image = np.zeros(shape=[256, 256], dtype=np.uint8)

cv2.circle(image, center=(50, 50), radius=10, color=(2, 2), thickness= -1)
cv2.circle(image, center=(100, 100), radius=10, color=(3, 3), thickness= -1)
cv2.circle(image, center=(150, 150), radius=10, color=(4, 4), thickness= -1)
cv2.circle(image, center=(75, 200), radius=10, color=(5, 5), thickness= -1)
cv2.circle(image, center=(200, 89), radius=10, color=(6, 6), thickness= -1)
cv2.circle(image, center=(21, 230), radius=5, color=(7, 7), thickness= -1)
cv2.circle(image, center=(149, 250), radius=5, color=(12, 12), thickness= -1)

plt.imshow(image)
plt.clim(min_value,max_value) 
plt.show()

相关问题