Python – 如何在不使用第三方库的情况下读取图像像素?

huangapple go评论63阅读模式
英文:

Python - How to read image pixels without using third-party libraries?

问题

使用OpenCV读取图像非常简单:

import cv2
im = cv2.imread("image.png")
print(im)

这会输出一个NumPy数组,其中数组项表示图像像素值,范围从0到255。

是否有一种方法可以使用Python标准库提取相同的像素值?预期的输出将采用Python内置数据结构的形式(例如列表/元组等)。例如:

[[191, 123, 100, 255],
 [233, 101, 120, 255],
 ...
]

到目前为止,我所拥有的是这个:

file = open("small.png", 'rb')
content = file.read()
print(content)

这将产生一个字节对象,但如何获取图像的实际像素值呢?

英文:

Reading an image using opencv is as easy as:

import cv2
im = cv2.imread("image.png")
print(im)

That outputs a numpy array with the array items representing the image pixel values ranging from 0 to 255.

Is there a way to extract those same pixel values using the Python standard library? The expected output would be in the form of Python builtin data structures (i.e. lists/tuples/etc). For example:

[[191, 123, 100, 255],
 [233, 101, 120, 255]
 ...
]

What I have so far is this:

file = open("small.png", 'rb')
content= file.read()
print(content)

and that will produce a bytes object, but how do I get the actual pixel values of the image?

答案1

得分: 1

没有标准库可以简单地从图像中读取像素字节。

你当然可以自己编写这样的模块,但这意味着要了解PNG格式,处理压缩图像数据等等。等你完成时,你将开发出自己的不太能胜任的版本的pillow

最好使用现有的模块来获取你想要的数据。

英文:

There is no simple solution to read pixels bytes from an image using the standard library.

You could certainly write such a module yourself, but that means understanding the PNG format, handling compressed image data, and so forth. By the time you're done, you have...developed your very own less capable version of pillow.

You are much better off using an existing module to get the data you want.

huangapple
  • 本文由 发表于 2020年1月3日 19:27:39
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577810.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定