如何使用 Go 编程语言读取彩色 png 文件并输出为灰度?
如何使用 Go 编程语言读取彩色 .png 文件,并将其输出为 8 位灰度图像?
How do I read in a color .png file in the Go programming language, and output it as an 8-bit grayscale image?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
我自己也遇到了这个问题,并提出了一个稍微不同的解决方案。我引入了一种新类型
Converted
,它实现了image.Image
。Converted
由原始图像和color.Model
组成。Converted
每次访问时都会进行转换,这可能会给出如果多次查看图像,性能会稍差,但另一方面它很酷且可组合。
I had this problem myself and came up with a slightly different solution. I introduced a new type,
Converted
, which implementsimage.Image
.Converted
consists of the original image and thecolor.Model
.Converted
does the conversion every time it is accessed, which could giveslightly worse performance if the image will be viewed multiple times, but on the other hand it is cool and composable.
下面的程序采用输入文件名和输出文件名。它打开输入文件,对其进行解码,将其转换为灰度,然后将其编码到输出文件。
该程序并不特定于 PNG,但要支持其他文件格式,您必须导入正确的图像包。例如,要添加 JPEG 支持,您可以添加到导入列表
_ "image/jpeg"
。如果您只想支持PNG,那么您可以使用image/png直接解码而不是image.Decode。
The program below takes an input file name and an output file name. It opens the input file, decodes it, converts it to grayscale, then encodes it to the output file.
Thie program isn't specific to PNGs, but to support other file formats you'd have to import the correct image package. For example, to add JPEG support you could add to the imports list
_ "image/jpeg"
.If you only want to support PNG, then you can use image/png.Decode directly instead of image.Decode.
@EvanShaw 的代码片段现在不起作用,(可能是某些 golang API 发生了变化)我对其进行了如下调整。遗憾的是确实输出了灰度图像,但内容很混乱,目前我不知道为什么。我这里提供给大家参考。
另外,golang 无法自动解码图像文件,我们需要直接使用图像类型的
Decode
方法。@EvanShaw 's snippet does not work now,(may be some golang API has change) I adapt it as below. sadly does output a grayscale image but the content is messy, currently I don't know why. I provide it here for your reference.
and by the way, golang wouldn't able to automatically decode image file, we need to directly use image type's
Decode
method.幸运的是我发现了这个,而且它有效!
https://godoc.org/github.com/harrydb/go/img /grayscale#Convert
一个完整的工作示例如下:
Luckily I found this, and it works!
https://godoc.org/github.com/harrydb/go/img/grayscale#Convert
A fully working example as follows:
简单的方法是使用 Intel OpenCV 库(开源)。Google 如何使用 opencv 读取图像。您将获得详细信息。
Easy way is use Intel OpenCV library (opensource).Google how to use opencv to read images. You will get details.