2
votes

I am trying to change the color of the image from RGB to grayscale using openCV, Python

My python code is as follows:

import cv2 ;
import numpy ;
img = cv2.imread(images/aiims.png) ;
gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY) ;
cv2.imshow('Original Image', img) ;
cv2.imshow('Gray Image', gray) ;

The Error That I am getting is :

File "test.py", line 11, in img = cv2.imread(images/aiims.png) ; NameError: name 'images' is not defined

I have already installed opencv and numpy.

I have the image in the image folder in the same directory, Please tell me if there is any flaw in my code, as I am very new to Python.

Thanks in Advance

2

2 Answers

2
votes

There are a few problems. To read in an image, you must place the path in quotes. Another problem is that your program is immediately closing after it displays an image. That's why the the image doesn't show. You need to add in cv2.waitKey(). From the docs

Its argument is the time in milliseconds. The function waits for specified milliseconds for any keyboard event. If you press any key in that time, the program continues. If 0 is passed, it waits indefinitely for a key stroke.

So in your case to display the image indefinitely, just pass in 0.

import cv2

img = cv2.imread("images/aiims.png")
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow('Original Image', img)
cv2.imshow('Gray Image', gray)
cv2.waitKey(0)

You can also read in a grayscale directly like this

import cv2

gray = cv2.imread("images/aiims.png", 0)
cv2.imshow('Gray Image', gray)
cv2.waitKey(0)
0
votes

Use and mention path in "" quotes

from PIL import Image