英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论