Image conversion Function using python and open
Question: Recently I have started learning opencv and python for image processing .I am
facing problems with writing a function .

I was given a task as follows:

_Write a function in python to open a color image and convert the image into
grayscale._

_You are required to write a function color_grayscale(filename,g) which takes
two arguments:_

    
    
      a. filename: a color image (Test color image is in folder “Task1_Practice/test_images”. Pick first image to perform the experiment.)
    
      b. g: an integer
    

_Output of program should be a grayscale image if g = 1 and a color image
otherwise._

The code i wrote is as follows :

    
    
    import cv2
    
    def color_grayscale(filename,g):
    
        filename = cv2.imread("a15.jpg")
        " Enter Value of g:"
        if g == 1:
            gray = cv2.cvtColor(filename, cv2.COLOR_BGR2GRAY)
            img = cv2.imshow("gray",gray)
        else:
            img = cv2.imshow("original",filename)
        return(img)
    
    color_grayscale("a15.jpg",1)
    

The code when run gives no output whatsoever.


Answer: `cv2.imshow` should be followed by `waitKey` function which displays the image
for specified milliseconds. Otherwise, it won’t display the image. For
example, `waitKey(0)` will display the window infinitely until any keypress
(it is suitable for image display). `waitKey(25)` will display a frame for 25
ms, after which display will be automatically closed. (If you put it in a loop
to read videos, it will display the video frame-by-frame)

Just add `cv2.waitKey(0)` before you return `img` and then it will display the
grayscale image

