仅使用原生python库-我可以对灰度值等数据进行图像处理吗



有没有办法使用Tkinter或其他原生python库从图像中获取灰度值?我通常使用Irfan视图打开图像并将其转换为B&W.我不允许安装任何库来测试这个项目-网络技术不允许这样做。所以我希望有一种方法可以做到这一点。如果可能的话,我想从这项工作中得到一个值的列表。

以下是仅使用tkinter将图像转换为灰度图像的示例:

import tkinter as tk
root = tk.Tk()
# load the image
img = tk.PhotoImage(file="sample.png")
# return grayscale data from image
data = root.tk.call(img, "data", "-grayscale")
# update image with grayscale data
img.put(data)
# show the grayscale image
tk.Label(root, image=img).pack()
root.mainloop()

请注意,tk.PhotoImage()仅支持PGM、PPM、GIF和PNG格式。


更新:将data值转换为(R, G, B)值的代码:

# function to convert hex color to (R,G,B)
# example: "#101010" -> (16, 16, 16)
def hex2rgb(hexcolor):
return int(hexcolor[1:3], 16), int(hexcolor[3:5], 16), int(hexcolor[5:7], 16)
pixels = []
for row in data:
pixels.append([hex2rgb(c) for c in row.split()])

最新更新