0

Example, I get the pixel value

from PIL import Image
im = Image.open("Lenna.png")
cordinate = x, y = 150, 59
# using getpixel method 
print (im.getpixel(cordinate));

output: (206, 92, 94)

How can I convert (206, 92, 94) into one integer value (in Python)?

Just like the function GetRGB(x,y) in Java and convert it back(integer value --> RGB --> setRGB value into image).

1
  • Your linked article explained the conversions rather well. What have you tried so far to implement it?
    – Klaus D.
    Jan 23, 2021 at 12:07

2 Answers 2

1

You can use struct.

import struct
str='aabbcc'
struct.unpack('BBB',str.decode('hex'))
//(170, 187, 204)

rgb = (50,100,150)
struct.pack('BBB',*rgb).encode('hex')
//'326496'
1

If you don't want to use the struct module, you can perform the calculations yourself:

def rgb2int(rgb): return (rgb[0]<<16)+(rgb[1]<<8)+rgb[2]
def int2rgb(N):   return (N>>16,(N>>8)%256,N%256)

rgb = (206,92,94)

print(rgb2int(rgb))      # 13524062
print(int2rgb(13524062)) # (206, 92, 94)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.