¿Cómo puedo encontrar la asignación de bits de un archivo PNG para los valores RGB?
He escrito el siguiente código en Python:
from PIL import Image
img = Image.open("art.png")
width, height = img.size
Rs = [["" for j in range(0, width)] for i in range(0, height)]
Gs = [["" for j in range(0, width)] for i in range(0, height)]
Bs = [["" for j in range(0, width)] for i in range(0, height)]
for x in range(width):
for y in range(height):
red, green, blue = img.getpixel((x,y))
rb = "{0:04b}".format(int(red / 16))
gb = "{0:04b}".format(int(green / 16))
bb = "{0:04b}".format(int(blue / 16))
Rs[y][x] = rb
Gs[y][x] = gb
Bs[y][x] = bb
print(Rs)
print(Gs)
print(Bs)
Sin embargo, me arroja un error que dice:
línea 20, en
red, green, blue = img.getpixel((x,y))
ValueError: se esperaban 3 valores al desempaquetar (se encontraron demasiados)
¿Cómo puedo solucionar esto?
davy.ai
El mensaje de error sugiere que se están devolviendo más de 3 valores mediante el método
getpixel()
, pero el código solo espera tres valores (para rojo, verde y azul).Puede solucionar esto agregando un paso adicional para convertir la imagen al modo RGB antes de obtener los valores de píxeles. Así es como puede modificar el código:
En este código modificado, primero convertimos la imagen al modo RGB utilizando el método
.convert("RGB")
. Esto asegura que cada valor de píxel devuelto porgetpixel()
tenga exactamente 3 valores para rojo, verde y azul. El resto del código es el mismo que antes.