使用 PPM 文件在 python 中将图像转换为 ASCII。不允许使用 PIL
项目需要一些帮助/指导。我们的任务是接收一个 .ppm 文件(我们需要测试的文件可以在这里找到:http://beastie.cs.ua.edu/cs250/projects/asciiart/tux.ppm)并使用 ascii 字符在屏幕上重新打印出来。我们需要将像素转换为灰度。这确实是我被困住的地方。无法弄清楚如何读取每三个元素(因为 PPM 文件中每三个元素都是一个像素),将它们转换为灰度并继续。再次强调 PIL 是不允许的。任何有关阅读内容的帮助或链接都很棒!
Needing a little help/direction with a project. Our task is to take in a .ppm file (the one we are required to test with is found here: http://beastie.cs.ua.edu/cs250/projects/asciiart/tux.ppm) and reprint it out on the screen using ascii characters. We are required to convert the pixels to greyscale. This is really where I am stuck. Cannot figure out how to read in every three elements (because every three is a pixel in PPM files), convert them to greyscale and move on. Again PIL is not allowed. Any help or links on what to read up on would be awesome!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PPM 并不难解析。
标题:
P3
表示图像是 ASCII 像素图(颜色)。50 50
是宽度和高度。255
是最大颜色值。正文:
只需删除所有换行符:
并将其解析为三元组(不太优雅):
The PPM isn't hard to parse.
The header:
P3
means that the image is an ASCII pixmap (color).50 50
is the width and height.255
is the max color value.The body:
Just remove all newlines:
And parse it in triplets (not too elegant):
读取 ppm 文件,您可以执行以下操作:
您实际上不需要了解文件的前 3 行。您只需知道您正在处理 RGB 图像,这意味着每个像素有 3 个值 (0-255)。
要将图像转换为灰度,您有两种选择:您可以生成另一个 PPM 文件(每个像素有 3 个值),也可以生成一个与 PPM 格式相同但第一行是
P2< 的 PGM 文件。 /code> 而不是
P3
并且每个像素只有一个值(这是一种很酷的方式)。要将 RGB 颜色值 (r,g,b) 转换为一个灰度强度值,您可以应用以下公式(比简单应用平均值更好):
生成每个像素一个值的灰度图像(如果您想要 3 个值)对于 r、g、b),您只需重复 3 次:
Reading the ppm file you can do this:
You really don't need to know about the 3 first lines of the file. You only must know that you are working with a RGB image, which means you have 3 values (0-255) for each pixel.
To convert the image to grayscale you have two options: you can either generate another PPM file (with 3 values per pixel) or you can generate a PGM file which has the same format as the PPM but the first line is
P2
instead ofP3
and you will have only one value per pixel (that's the cool way).To convert a RGB color value (r,g,b) in one grayscale intensity value you can apply this formula (better than simply apply the average):
Generate the grayscale image with one value per pixel (if you want it in 3-values you only have to repeat 3 times it for r,g,b):