3DG
3DG

Reputation: 45

Is there a way to get an RGB value of a pixel on a frame of a GIF in PIL?

I am currently working on a discord bot with Pycord. I am working on adding support for GIF images on the currently existing image commands, and I need the color of the pixels. When I try to get the color of an exact point in PIL/Pillow, I get a number representing the color of the pixel in the GIF color table, which is not what I want. Even when I convert the image to RGBA, I still get only the index, nothing else. When I google it, all I see is multitudes of this same method that I tried.

Here is a basic program to demonstrate what I have tried:

from io import BytesIO as toimg
from PIL import Image, ImageFont, ImageDraw, ImageOps, ImageSequence
      #reqdata is gif data from a url
      imggif = Image.open(toimg(reqdata.content))
      for frame in ImageSequence.Iterator(imggif):
        img = frame.convert("RGBA")
        img = img.convert("RGBA") # might not need this due to the line above but idk
        img = ImageOps.grayscale(img) # this line was not here before, edited it in.
        width, height = img.size
        for y in range(height):
          for x in range(width):
            print(img.getpixel((x,y))) # this prints out only one number, i need an RGBA value (4 numbers)

If anyone can help, that would be very appreciated!

Edit: I found out the solution and I realized that it was not the frame itself, but instead it was because I grayscaled the image after converting it. The program was created based on what I thought was the mistake, and I didn't even check it! This was nowhere in the question and i apologize for not thinking to look at such a simple thing before posting this question. I had to convert back to RGBA after grayscaling the image. :(

Edit 2: I am just now realizing that this is going to be my very last question, and that I should have looked further to realize my incredibly simple mistake before wasting my last chance on this site i will ever have. It's for the better, I'm a dumbass who is unable to realize such simple things. I will not be and have not been needed on this site.

Upvotes: 0

Views: 1231

Answers (2)

Juicestus
Juicestus

Reputation: 612

Try

r, g, b, a = img.getpixel((x, y))

I tested this and it works for me. Based on [this post]. (Get pixel's RGB using PIL)

Edit: another approach that has worked for me in the past is to use pixels = img.load() and index a pixel like pixels[x, y]

Upvotes: 2

Flip
Flip

Reputation: 1

This worked for me

    from PIL import Image
    
    red_image = Image.open("red.png")
    red_image_rgb = red_image.convert("RGB")
    rgb_pixel_value = red_image_rgb.getpixel((10,15))
    print(rgb_pixel_value) #Prints (255, 0, 0) 

Upvotes: 0

Related Questions