且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

改变RGB颜色的色调

更新时间:2023-01-27 09:53:48

一次性完成所有替换的解决方案:

Here is the solution to do all the replacement in one go :

import matplotlib.colors as clr
import matplotlib.pyplot as plt
import numpy as np


N = 100000
x = 1.2 + 800.0 * np.random.rand(N)
y = 1.2 + 800.0 * np.random.rand(N)
# Generate random colors of the form (r, g, b, a) where r = 0.0
colors = np.random.rand(4 * N).reshape((N, 4))
colors[:, 0] = 0.0
area = np.pi * (5 * np.random.rand(N))**2

fig = plt.figure()
ax = fig.add_subplot(1, 1, 1)
pcol = ax.scatter(x, y, s=area, c=colors)
ax.set_xscale('log')
ax.set_yscale('log')

# Save initial figure
plt.savefig("hue.jpg")

oldRGBA = pcol.get_facecolors().reshape((N, 1, 4))
oldRGB = oldRGBA[:, :, :3]
newRGB = oldRGB
newRGB[:, :, 0] = 1.0 # Set red component to 1.0
oldHSV = clr.rgb_to_hsv(oldRGB)
newHSV = clr.rgb_to_hsv(newRGB)
oldHSV[:, :, 0] = newHSV[:, :, 0]
newRGBA = np.copy(oldRGBA)
newRGBA[:, :, :3] = clr.rgb_to_hsv(oldHSV)
pcol.set_facecolors(newRGBA[:, 0, :])

# Save modified figure
plt.savefig("hue_bis.jpg")

plt.close()

如您所见,此代码尝试绘制100000点,实际上它在大约2秒钟内就成功做到了。这是产生的数字:

As you can see, this code attempts to plot 100000 points and in fact it managed to do this in about 2 seconds. Here are the figures produced :

和:

最后两个问题:


如何在保留A的alpha值的同时将给定的RGBA颜色A的色调更改为给定的RGB颜色B的色调?

How do I change the hue of a given RGBA color A to that of a given RGB color B while preserving the alpha value of A ?

和:


将使用其他颜色模型(例如HSL)简化任务,如果是,

Would using a different color model (HSL for example) simplify the task, and if so, which would help

我认为您进行此类修改的方法很可观,它避免了手工计算(请参见 HSL和HSV )。可以使用其他颜色模型,HSL和HSV都可以在不影响其他参数的情况下更改色相,但这只是另一种方法,而不是更好的方法。

I think that your approach to do such a modification is appreciable, it avoids making calculations by hand (see HSL and HSV). Using a different color model is possible, both HSL and HSV allow to change the hue without affecting other parameters, but that is only an other way to do it and not a better one.

希望这会有所帮助。