问题描述
有没有办法使用 Tkinter 或其他本机 python 库从图像中获取灰度值?我通常使用 Irfan 视图打开图像并将其转换为黑白。我不允许安装任何库来测试这个项目——网络技术不允许。所以我希望有一种方法可以做到这一点。如果可能的话,我想要一份这份工作的价值清单。
解决方法
以下是仅使用 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,B)
# example: "#101010" -> (16,16,16)
def hex2rgb(hexcolor):
return int(hexcolor[1:3],16),int(hexcolor[3:5],int(hexcolor[5:7],16)
pixels = []
for row in data:
pixels.append([hex2rgb(c) for c in row.split()])