Reputation: 3751
I have found the following two ways to create an image:
Using PIL
from PIL import Image
import numpy as np
data = np.arange(1 * 2048).reshape(1, 2048)
print(data)
img = Image.fromarray(data, 'RGB')
img.save('my.png')
Using Matplotlib
import matplotlib.pyplot as plt
import matplotlib.cm as cm
import numpy as np
plt.imsave('filename.png', np.arange(1 * 2048).reshape(1, 2048))
They both work just fine. However, I cannot get either method to follow my data format.
My array is a 2 dimensional array that is 32x1000
.
each element is a number between 0 to 255.
I want each element to be drawn as a pixel with a the RGB color that is returned as a result of the following method.
def get_rgb_by_int(rgb_int):
return rgb_int & 255, (rgb_int >> 8) & 255, (rgb_int >> 16) & 255
Essentially, I want to know if there is a way to create an image using the same arrays where each element is now another array that represents the [r,g,b]
rather than int
.
Edit After calling that: This is what I have:
print(result.shape)
>> (32, 1000)
print(result[0])
>> [(7, 0, 0)...(13, 0, 0)]
I would like the image generated to be 1000 wide and 32 high. The first pixel should be of RGB value (7, 0, 0)
and the last pixel of the first row should be (13, 0, 0)
. Each element in result
represent a single row.
Upvotes: 1
Views: 6673
Reputation: 2481
The way to do it is with numpy
. If you have an array (doesn't matter how it was constructed) that looks like: A = [[R, G, B], [R, G, B], ...
, then you can do:
import numpy as np
A = np.array(A).reshape(-1, 3)
And now A
will have the shape N x 3
, where the 3
dimension is RGB. If you know the sizes of the final image, you can do
np.array(A).reshape(N, M, 3)
and it will re-shape your array into RGB as you need. Then once you have the numpy array, you have your array in the shape of an image and can save it to PNG, etc.
Upvotes: 1