简体   繁体   English

解释图像的字节数组

[英]Interpret byte array of an image

What is stored in the byte array of an image? 图像的字节数组中存储了什么? I was working on a project in which it was needed to interpret what is stored in the byte array of an image. 我在一个项目中工作,该项目需要解释存储在图像字节数组中的内容。 How do we interpret the elements of the byte array? 我们如何解释字节数组的元素?

Note: Following is the code in python to generate the byte array 注意:以下是python中生成字节数组的代码

from array import array
f = open("temp.jpg", "rb")
bytes = bytearray(f.read())

You've tagged this with python-imaging-library, but you don't mention it anywhere in your question, and you aren't using it. 您已经用python-imaging-library标记了它,但是您在问题中的任何地方都没有提及它,并且您没有使用它。

I strongly suspect that you actually want to be using it. 我强烈怀疑您确实使用它。 You're not interested in the array of bytes that make up the JFIF header, compressed image data, EXIF segment, etc.; 您对组成JFIF标头,压缩图像数据,EXIF段等的字节数组不感兴趣; you want an array of pixel values . 您需要一个像素值数组。

So, first you have to install the Python imaging library. 因此,首先您必须安装Python映像库。 The modern version is named Pillow , and the docs have completely installation instructions, but often it's just pip install pillow . 现代版本名为Pillow ,并且文档中有完整的安装说明,但通常只是pip install pillow

And now, you can use it in your script: 现在,您可以在脚本中使用它:

>>> from PIL import Image
>>> img = Image.open("temp.jpg")
>>> img.mode
'RGB'
>>> img.getpixel((0, 0))
(3, 148, 231)

An Image object is sort of array-like already. Image对象已经有点像数组了。 The mode lets me know that this is an 8-bit RGB image, so each pixel will have 3 values—red, green, and blue intensities from 0 to 255. And the getpixel((0, 0)) returns me the red, green, and blue values for the top-left pixel. mode让我知道这是一个8位RGB图像,因此每个像素将具有3个值-红色,绿色和蓝色强度,范围为0到getpixel((0, 0))返回红色,左上角像素的绿色和蓝色值。

If you really want a flat array, you can go that too: 如果您真的想要平面阵列,也可以这样做:

>>> img.getdata()[0]
(3, 148, 231)

Or, if you want a flat array of bytes (alternating red-blue-green-red-blue-green) instead of tuples: 或者,如果您想要一个字节的平面数组(交替显示红色-蓝色-绿色-红色-蓝色-绿色)而不是元组:

>>> img.getbytes()[0]
3

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

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