简体   繁体   English

如何将1通道numpy矩阵转换为4通道单色图像

[英]How to convert 1-channel numpy matrix to 4-channel monochromatic image

I am working on a pyqt project with numpy and cv2. 我正在使用numpy和cv2进行pyqt项目。 Basically, I want to use a binary numpy mask (1024, 1024) to create a 4 channel monochromatic image (1024, 1024, 4) , where all 1s from the mask are pink and all 0s are invisible. 基本上,我想使用二进制numpy蒙版(1024, 1024) 1024,1024 (1024, 1024)创建一个4通道单色图像(1024, 1024, 4) ,其中蒙版中的所有1为粉红色,所有0为不可见。 Then I convert the image and show it as overlay in my QScene to highlight some pixels in another image. 然后,我转换图像并将其显示为QScene中的叠加层,以突出显示另一幅图像中的某些像素。

My current approach does the job, but is too slow and I'm sure that numpy provides something more convenient. 我目前的方法可以完成任务,但是速度太慢,并且我可以确定numpy提供了一些更方便的方法。

color = (255, 0, 238, 100)
r = (mask * color[0]).reshape((w*h))
g = (mask * color[1]).reshape((w*h))
b = (mask * color[2]).reshape((w*h))
a = (mask * color[3]).reshape((w*h))

rgba = np.dstack((r, g, b, a)).reshape((w, h, 4))
transposed = np.transpose(rgba, axes=[1, 0, 2])

Is there a better way to show a mask overlay? 有没有更好的方法来显示蒙版覆盖? I don't insist on using numpy, however, it is important that I can set the color, as I will be needing several colors. 我不坚持使用numpy,但是设置颜色非常重要,因为我将需要几种颜色。

Yes! 是! Use NumPy broadcasting to clean it up and have a one-liner , like so - 使用NumPy broadcasting将其清理并形成one-liner ,就像这样-

transposed = mask.T[...,None]*color

Explanation: 说明:

  1. Use mask.T to do the np.transpose operation done at the end. 使用mask.T完成最后的np.transpose操作。
  2. Use [...,None] on the transposed array to basically push all its dimensions to the front and create a singleton dim (dim with length=1 ) as the last axis. 在转置数组上使用[...,None]基本将其所有尺寸推到最前面,并创建一个单例暗淡( length=1暗淡)作为最后一个轴。 For introducing this new axis, we have used an alias for np.newaxis - None . 为了引入这个新轴,我们为np.newaxis - None使用了别名。 Thus, we would achieve broadcasting for the transposed array along its last axis aligned with the elements of color . 因此,我们将沿着其最后一个与color元素对齐的轴实现转置数组的广播。
  3. Finally, we perform the element-wise multiplication itself, which in fact would be a broadcasted operation. 最后,我们自己执行逐元素乘法,实际上这是broadcasted操作。

You can perform the creation of new axis part at the start and then use np.transpose or np.swapaxes and this would be closer to your original code. 您可以在开始时执行新轴零件的创建,然后使用np.transposenp.swapaxes ,这将更接近您的原始代码。 So, alternatively we could have : 因此,或者我们可以:

transposed = mask[:,:,None].transpose(1,0,2)*color

and, 和,

transposed = mask[:,:,None].swapaxes(0,1)*color

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM