2

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 Answers 2

2

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)
Sign up to request clarification or add additional context in comments.

Comments

1

Use and mention path in "" quotes

from PIL import Image

6 Comments

Can you please elaborate the above code line that you mentioned
aur use import Image
I added the path in quotes, now my program runs but in run time i am not able to see any image . the two windows opens but they does not respond. and not able to see any image in both the windows
if you can . please run the above code in your system, and please tell me If and what is the problem is my code. . Thanks in advance
2 window because you menstion 2 time show. Its working . but at show time you not correctly show image .. -> try this cv2.imshow('image',img)
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.