我有一张灰度图像,它只有 1 个通道。我使用的代码要求所有图像都有三个通道。如何使用一些 Linux 命令将我的图像转换为 3 通道图像?
这是我收到的错误,我不想更改代码,而是想更改图像:
Traceback (most recent call last):
File "get_img_vec.py", line 22, in <module>
nd_arr = img2vec.get_vec(img)
File "../img_to_vec.py", line 43, in get_vec
h_x = self.model(image)
File "/scratch/sjn-p3/anaconda/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "/scratch/sjn-p3/anaconda/anaconda3/lib/python3.6/site-packages/torchvision-0.2.1-py3.6.egg/torchvision/models/resnet.py", line 139, in forward
File "/scratch/sjn-p3/anaconda/anaconda3/lib/python3.6/site-packages/torch/nn/modules/module.py", line 477, in __call__
result = self.forward(*input, **kwargs)
File "/scratch/sjn-p3/anaconda/anaconda3/lib/python3.6/site-packages/torch/nn/modules/conv.py", line 301, in forward
self.padding, self.dilation, self.groups)
RuntimeError: Given groups=1, weight of size [64, 3, 7, 7], expected input[1, 1, 224, 224] to have 3 channels, but got 1 channels instead
图片:
$ identify 10524.jpg
0524.jpg JPEG 1050x550 1050x550+0+0 8-bit PseudoClass 256c 80.7KB 0.000u 0:00.000
这是图片:
答案1
以下 Python 代码有效:
import cv2
import numpy as np
img = cv2.imread('10524.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img2 = np.zeros_like(img)
img2[:,:,0] = gray
img2[:,:,1] = gray
img2[:,:,2] = gray
cv2.imwrite('10524.jpg', img2)
答案2
如果需要,安装 ImageMagick:
sudo apt install imagemagick
(你也可以在 Ubuntu 18.04 上从源代码安装最新版本,如下所示本指南)
要分离图像通道,请运行:
convert rose: -channel R -separate separate_red.gif convert rose: -channel G -separate separate_green.gif convert rose: -channel B -separate separate_blue.gif
(下列的本指南)
或者合并 RGB 图像通道,运行:
convert separate_red.gif separate_green.gif separate_blue.gif \ -combine -set colorspace sRGB rose_combined.gif
(下列的本指南)
这也适用于 JPG。您还可以尝试将相同灰度图像的副本与 3 个不同的通道组合在一起。