简体   繁体   English

如何在python中获取图像像素的RGBA颜色值

[英]How to get RGBA color value of an image pixel in python

I'm trying to convert this java code to python: 我正在尝试将此Java代码转换为python:

BufferedImage image;
FileInputStream fstream1 = new FileInputStream("image.png")
image = ImageIO.read(fstream1);
int max = -40000000; //Java rgb returns negative values

for (int i = 0; i < 128; i++)
{
    for (int j = 0; j < 255; j++)
    {
        color = image.getRGB(j, i); //returns integer
.....

I tried this in python: 我在python中尝试过这个:

from PIL import Image

image = Image.open("image.png").convert("RGBA")
pixels = image.load()

for i in range(128):
    for j in range(255):
        color = pixels[j, i] #returns (R, G, B, A);

The problem however is that i'm getting different values in python. 但是问题是我在python中得到了不同的值。

Why does java returns negative integer values and how do i get the same result in python? 为什么Java返回负整数值,我如何在python中得到相同的结果?

This function should convert a colour from the Python format to the Java format: 此函数应将颜色从Python格式转换为Java格式:

def convertPixel(c):
    x = c[0] << 16 | c[1] << 8 | c[2] | c[3] << 24
    if x >= 1<<31:
        x -= 1<<32
    return x

Note that Python's format is perfectly sane - it gives you the exact R, G, B and A values directly. 请注意,Python的格式完全是理智的-直接为您提供确切的R,G,B和A值。 It's Java that has the weird format. 奇怪的是Java。

You get negative values in Java because of integer overflow - for example 0xFFFFFFFF (or 4294967295), which is pure white, wraps around to -1. 由于整数溢出,您在Java中会得到负值-例如0xFFFFFFFF (或4294967295),它是纯白色,环绕到-1。

The Java getRGB() value is a signed 32-bit integer with the alpha, R, G and B values in each of the 8 bits from most to least significant bytes. Java getRGB()值是一个带符号的32位整数,在从最高有效字节到最低有效字节的8位中的每一个中都有alpha,R,G和B值。

You can 'reproduce' the same value with: 您可以使用以下方法“复制”相同的值:

def packRGBA(r, g, b, a)
    val = a << 24 | r << 16 | g << 8 | b
    if a & 0x80:
        val -= 0x100000000
    return val

color = packRGBA(*pixels[j, i])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM