Reputation: 41
This seems like a dumb question at first--just read the docs!--but I did, and can't figure out how I can read a file, and get an RGB value. Simply, it isn't clear what anything means.
Could someone please show me how I could read a file correctly, with RGB data?
Upvotes: 3
Views: 2707
Reputation: 11
Found no answer to this useful question so here's what I came up with (docs didn't help) :
# Reading the png metadata
image = png.Reader(filename='test.png').asDirect()
# Conversion from weird objects to normal lists
pixels = [list(row) for row in image[2]]
print(pixels)
Output with a 4 pixel square image with some black and orange :
[[13, 6, 2, 248, 124, 38], [246, 123, 38, 16, 8, 2]]
Where each sub-list is a row of pixels, with R, G, B, R, G, B, R ...
Upvotes: 1
Reputation: 158
Having read the docs I understand your confusion. I will refer to an answer made by Constantin, using the following code should do the job:
import png, array
point = (2, 10) # coordinates of pixel to be painted red
reader = png.Reader(filename='image.png')
w, h, pixels, metadata = reader.read_flat()
pixel_byte_width = 4 if metadata['alpha'] else 3
pixel_position = point[0] + point[1] * w
new_pixel_value = (255, 0, 0, 0) if metadata['alpha'] else (255, 0, 0)
pixels[
pixel_position * pixel_byte_width :
(pixel_position + 1) * pixel_byte_width] = array.array('B', new_pixel_value)
output = open('image-with-red-dot.png', 'wb')
writer = png.Writer(w, h, **metadata)
writer.write_array(output, pixels)
output.close()
Upvotes: 1