Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to read an image in Python OpenCV

I am trying to read and display an image in Python OpenCV.

Executing the following code:

import cv2 import numpy as np import matplotlib.pyplot as plt  img = cv2.imread('dumb.jpg', cv2.IMREAD_GRAYSCALE)  cv2.imshow('image',img) cv2.waitKey(0) cv2.destroyAllWindows() 

Results in the following error:

cv2.error: C:\build\master_winpack-bindings-win64-vc14-static\opencv\modules\highgui\src\window.cpp:325: error: (-215) size.width>0 && size.height>0 in function cv::imshow

How to solve this?

NOTE: I have all the prerequisites needed to execute this (python 2.7, opencv 3.3 matplotlib, numpy)

like image 696
Nagaraj Avatar asked Oct 03 '17 08:10

Nagaraj


People also ask

How do I open an image in OpenCV Python?

In OpenCv module,we can use the function cv2. imread() to read an image. When inputting the image path, the image should be in the working directory or a full path of image should be given.

How do you read in images in Python?

We use cv2. imread() function to read an image. The image should be placed in the current working directory or else we need to provide the absoluate path.


2 Answers

If you are trying to display OpenCV image using matplotlib, use the code below.

import numpy as np import cv2 import matplotlib.pyplot as plt %matplotlib inline  # if you are running this code in Jupyter notebook  # reads image 'opencv-logo.png' as grayscale img = cv2.imread('/path_to_image/opencv-logo.png', 0)  plt.imshow(img, cmap='gray') 
like image 59
ksp585 Avatar answered Sep 21 '22 22:09

ksp585


there is a tutorial on http://docs.opencv.org/3.1.0/dc/d2e/tutorial_py_image_display.html

 import numpy as np  import cv2   # Load an color image in grayscale  img = cv2.imread('/path_to_image/messi5.jpg',0)   # show image   cv2.imshow('image',img)  cv2.waitKey(0)  cv2.destroyAllWindows() 

use an absolute path to the image then you have no path problems

https://en.wikipedia.org/wiki/Path_(computing)#Absolute_and_relative_paths

OpenCV Error: (-215)size.width>0 && size.height>0 in function imshow

like image 32
ralf htp Avatar answered Sep 24 '22 22:09

ralf htp