Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

imshow doesn't show the correct RGB values

I’m confused why my canvas class produce only 255 colors that is colors that are the pure red in this case.

Although my code specifies darker tones of red for the colors of the different pixels, the resulting image linked below the code shows the same color for each pixel.

Code to reproduce.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

class Canvas():
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.pixels = np.zeros((y,x,3))

    def _center2pixel(self, x, y):
        return (self.y//2 - y, self.x//2 + x)

    def write_pixel(self, x, y, color):
        x,y = self._center2pixel(x,y)
        self.pixels[x,y] = color

    def show(self):
        plt.imshow(self.pixels, vmin=0, vmax=255)
        plt.show()

    
canvas = Canvas(10,10)


canvas.write_pixel(0,0,np.array([255,0,0])*0.1)
canvas.write_pixel(1,0,np.array([255,0,0]))
canvas.write_pixel(2,0,np.array([10,0,0]))
canvas.write_pixel(3,0,np.array([25.5,0,0]))
canvas.show()

4 pixels with the same color value although they were designed to have different color values

Are you able to help me resolve this? What am I doing wrong?

Moreover, I get a warning that it has clipped the input, and that it should be between 0 and 255 – which it is.

I tried to specify different colors, but the same color shows up on the plot.

>Solution :

All of your arrays contain floats, which is the numpy default. When you use floats for RGB, they must be between 0 and 1, which is exactly what the error message tells you. Your values are all greater than 1, and so are fully saturated.

You have two choices. Either use dtype=np.uint8 to turn your colors into integers, or change your range to [0,1]:

canvas.write_pixel(0,0,np.array([1,0,0])*0.1)
canvas.write_pixel(1,0,np.array([1,0,0]))
canvas.write_pixel(2,0,np.array([0.04,0,0]))
canvas.write_pixel(3,0,np.array([0.1,0,0]))
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading