0

I am starting a little project and I am having some difficulty in finding the answer that I am looking for. I don't really know exactly what terms I should be using to search, and couldn't find anything similar so I am sorry if this has been asked previously.

I am essentially trying to have a 2D plot of a set size, 300x300 for example full of random RGB pixels. I have figured out how to plot them with imshow and remove the axis labels so far, but it looks odd like it is zoomed in too far. Also, I know I can use RGB arguements in imshow, but the matplotlib manual touches on it, but never gives any examples. The closest cmap I have found to RGB is hsv so I am using that for now until I find the RGB solution.

Can anyone help me with assigning a random RGB value to each pixel instead of using cmap, and maybe adjusting the apparent size of the image so the pixels are less "zoomed in"? I am open to using something other than imshow for flexibility, it is just the only thing I found to do what I want. Thank you very much in advance!

import matplotlib.pyplot as plt
import matplotlib.cm as cm
from numpy import random

Z = random.random((300,300))
plt.imshow(Z, cm.get_cmap("hsv"), interpolation='nearest')
plt.axis('off')
plt.show()
Confused
  • 15
  • 3
  • Why did you choose `matplotlib`? You can use PIL to create images from numpy arrays and either display them or save them as image files. If you are trying to blend with some other `matplotlib` stuff, then that's a different story. – Tim Roberts Aug 18 '22 at 22:28
  • Thank you for the comment! I read about PIL and it does look like a good solution, but down the road I would like to have some integration with matplotlib functions. – Confused Aug 18 '22 at 22:32
  • Remember, that imshow is going to stretch your 300x300 plot to fit the window. That's why your pixels appear large. – Tim Roberts Aug 18 '22 at 22:33
  • Thank you very much for the code and for the explanation, I will see what I can do with this! – Confused Aug 18 '22 at 22:36
  • Does this answer your question? [Specifying and saving a figure with exact size in pixels](https://stackoverflow.com/questions/13714454/specifying-and-saving-a-figure-with-exact-size-in-pixels) – Jody Klymak Aug 18 '22 at 23:56
  • So I have been playing around with everything and the PIL code is exactly what I am looking for as far as format, but I think I need to do it in matplotlib for data visualization and manipulation. Thank you Jody for the thread about resizing, that should be helpful! – Confused Aug 19 '22 at 13:32

1 Answers1

1

Here's how you do it with PIL:

from PIL import Image
import numpy as np

data = (np.random.random( (300,300,3) ) * 256).astype(np.uint8)
img = Image.fromarray(data)
img.show()
img.save('rand.png')
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30