Search code examples
pythonarraysvalueerror

ValueError in Python, Number of Indices in Array not Matching


I'm supposed to write a method that converts an RGB image to Grayscale by using the "average method" where I take the average of the 3 colors (NOT the weighted method or luminosity method). I then must display the original RGB image and grayscale image next to each other (concatenated). The language I'm writing in is Python. This is what my code looks like currently.

import numpy as np
import cv2

def average_method(img):
    grayValue = (img[:,:,2] + img[:,:,1] + img[:,:,0])/3
    gray_img = grayValue.astype(np.uint8)
    return gray_img

def main():
    img1 = cv2.imread('html/images/sunflowers.jpg')
    img1 = cv2.resize(img1, (0, 0), None, .25, .25)
    img2 = average_method(img1)
    numpy_concat = np.concatenate((img1, img2), 1)
    cv2.imshow('Numpy Concat', numpy_concat)
    cv2.waitKey(0)
    cv2.destroyAllWindows

if __name__ =="__main__":
    main()

When I try to run this, it shows me this error:

    Traceback (most recent call last):
  File "test.py", line 23, in <module>
    main()
  File "test.py", line 16, in main
    numpy_concat = np.concatenate((img1, img2), 1)
  File "<__array_function__ internals>", line 5, in concatenate
ValueError: all the input arrays must have same number of dimensions, but the array at index 0 has 3 dimension(s) and the array at index 1 has 2 dimension(s)

Can someone please help me figure this out so that I can successfully have RGB and grayscale side by side by using the "average method"? Not sure if I'm setting up the average method correctly and it causes this issue, or if it's from how I try to concatenate the pictures. Thanks.


Solution

  • The error message pretty much tells you what is going on. Your img2 is now a greyscale (single-channel) image, which img1 is still, obviously, colour (three-channel).

    I am no numpy wizard, so there might be a better solution, but I think you can expand img2 to three channels using

    img2 = np.stack(3 * [img2], axis=2)
    

    Edit: possibly more efficient (and harder to understand):

    img2 = np.repeat(A[..., np.newaxis], 3, axis=2)