简体   繁体   English

如何使用opencv为python编写灰色(1通道)图像

[英]how to write gray (1-channel) image with opencv for python

I just would like to know if it's possible to save gray 1 channel images with opencv starting from rgb images. 我只是想知道是否有可能从rgb图像开始使用opencv保存灰色1通道图像。

import cv2
bgr_img = cv2.imread('anyrgbimage.jpg')
print(bgr_img.shape) #(x,y,3)
gray_img = cv2.cvtColor(bgr_img,cv2.COLOR_BGR2GRAY)
cv2.imwrite('hopefully_gray_image.jpg',gray_img)
#cv2.imwrite('hopefully_gray_image.jpg',gray_img,[int(cv2.COLOR_BGR2GRAY)])
buh_img = cv2.imread('hopefully_gray_image.jpg')
print(buh_img.shape) #(x,y,3)

i know i can add some parameters inside cv2.imwrite, but i can't figure out what. 我知道我可以在cv2.imwrite中添加一些参数,但是我不知道是什么。

Yes, it is. 是的。 Let me elaborate on @Miki's comment to your answer. 让我详细说明@Miki对您的答案的评论 If you take a look at the documentation of imread(filename[, flags]) , you will see that the default flag is cv2.IMREAD_COLOR , ie, OpenCV will load the image with 3 channels, by default (even if it has 1 or 4 channels). 如果查看imread(filename[, flags])的文档,您会看到默认标志为cv2.IMREAD_COLOR ,即,默认情况下,OpenCV将使用3个通道加载图像(即使它具有1或4个频道)。 If you want to use the same imread(...) to load both three- and single-channel images, you should use the flag cv2.IMREAD_UNCHANGED . 如果要使用相同的imread(...)加载三通道和单通道图像,则应使用标志cv2.IMREAD_UNCHANGED In practice, how does that work? 实际上,这是如何工作的?

import cv2
import numpy as np

img = (np.random.random((300, 300, 3)) * 255.).astype(np.uint8)
# let's save 4 images (color/gray, png/jpg)
cv2.imwrite('img-png-color.png', img)          # output size: 270KB
cv2.imwrite('img-png-gray.png', img[:, :, 1])  # output size: 90KB
cv2.imwrite('img-jpg-color.jpg', img)          # output size: 109KB
cv2.imwrite('img-jpg-gray.jpg', img[:, :, 1])  # output size: 93KB

There are two things to note: 有两件事要注意:

  • The color PNG image file is 3x larger than the gray PNG image; 彩色PNG图像文件比灰色PNG图像大3倍;
  • JPEG is working well, ty :) JPEG运作良好,ty :)

Now, if you read ANY of these images using the default flag, they will be loaded with a shape of (300, 300, 3). 现在,如果您使用默认标志读取这些图像中的任何图像,它们将以(300,300,3)的形状加载。 However, if you proceed as @Miki told you: 但是,如果按照@Miki告诉您的步骤进行操作:

cv2.imread('img-png-color.png', cv2.IMREAD_UNCHANGED).shape  # (300, 300, 3)
cv2.imread('img-png-gray.png', cv2.IMREAD_UNCHANGED).shape   # (300, 300)
cv2.imread('img-jpg-color.jpg', cv2.IMREAD_UNCHANGED).shape  # (300, 300, 3)
cv2.imread('img-jpg-gray.jpg', cv2.IMREAD_UNCHANGED).shape   # (300, 300)

Therefore, in fact, the gray images were "saved" as single-channel. 因此,实际上,灰度图像被“保存”为单通道。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM