M HYPE SPLASH
// updates

Convert a 1 channel image to a 3 channel image

By Emma Terry

I have a grayscale image that has only 1 channel. I am using a code that expects all images to have three channels. How can I convert my image to a 3 channel image using some Linux commands?

Here is the error I get and I do not want to change the code, rather I want to change the image:

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/", 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

The image:

$ identify 10524.jpg
0524.jpg JPEG 1050x550 1050x550+0+0 8-bit PseudoClass 256c 80.7KB 0.000u 0:00.000

This is the image:

black and white photo of a face

2 Answers

The following Python code works:

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)
  1. Install ImageMagick if needed:

    sudo apt install imagemagick

(You can also install the latest release from source on Ubuntu 18.04 following this guide)

  1. To separate image channels run:

     convert rose: -channel R -separate separate_red.gif convert rose: -channel G -separate separate_green.gif convert rose: -channel B -separate separate_blue.gif

    (following this guide)

    or to combine RGB image channels run:

    convert separate_red.gif separate_green.gif separate_blue.gif \ -combine -set colorspace sRGB rose_combined.gif

    (following this guide)

This will work for JPG too. Also you can try combining copies of the same gray-scale images with 3 different channels.

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy