es.davy.ai

Preguntas y respuestas de programación confiables

¿Tienes una pregunta?

Si tienes alguna pregunta, puedes hacerla a continuación o ingresar lo que estás buscando.

¿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?

Tags:  , , ,

Answer

  1. Avatar for 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:

    from PIL import Image
    
    img = Image.open("art.png").convert("RGB") # convierte la imagen al modo RGB
    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)
    

    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 por getpixel() tenga exactamente 3 valores para rojo, verde y azul. El resto del código es el mismo que antes.

Comments are closed.