如何解决仅使用本机 python 库 - 我可以对灰度值等数据进行图像处理吗?
有没有办法使用 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()])
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。