How can one display an image using cv2 in Python - python

I've been working with code to display frames from a movie. The bare bones of the code is as follows:
import cv2
import matplotlib.pyplot as plt
# Read single frame avi
cap = cv2.VideoCapture('singleFrame.avi')
rval, frame = cap.read()
# Attempt to display using cv2 (doesn't work)
cv2.namedWindow("Input")
cv2.imshow("Input", frame)
#Display image using matplotlib (Works)
b,g,r = cv2.split(frame)
frame_rgb = cv2.merge((r,g,b))
plt.imshow(frame_rgb)
plt.title('Matplotlib') #Give this plot a title,
#so I know it's from matplotlib and not cv2
plt.show()
Because I can display the image using matplotlib, I know that I'm successfully reading it in.
I don't understand why my creation of a window and attempt to show an image using cv2 doesn't work. No cv2 window ever appears. Oddly though, if I create a second cv2 window, the 'input' window appears, but it is only a blank/white window.
What am I missing here?

As far as I can see, you are doing it almost good. There is one thing missing:
cv2.imshow('image',img)
cv2.waitKey(0)
So probably your window appears but is closed very very fast.

you can follow following code
import cv2
# read image
image = cv2.imread('path to your image')
# show the image, provide window name first
cv2.imshow('image window', image)
# add wait key. window waits until user presses a key
cv2.waitKey(0)
# and finally destroy/close all open windows
cv2.destroyAllWindows()
I think your job is done then

Since OpenCV reads images with BGR format, you'd convert it to RGB format before pass the image to pyplot
import cv2
import matplotlib.pyplot as plt
image = cv2.imread('YOUR_FILEPATH')
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
plt.imshow(image)
plt.show()

While using Jupyter Notebook this one might come in handy
import cv2
import matplotlib.pyplot as plt
# reading image
image = cv2.imread("IMAGE_PATH")
# displaying image
plt.imshow(image)
plt.show()

import cv2
image_path='C:/Users/bakti/PycharmProjects/pythonProject1/venv/resized_mejatv.jpg'
img=cv2.imread(image_path)
img_title="meja tv"
cv2.imshow(img_title,img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Related

VsCode matplotlib doesnt show figure window

import cv2
import matplotlib.pyplot as plt
import numpy as np
img = cv2.imread("Desktop\sudoku.jpg", 0)
img = np.float32(img)
plt.figure()
plt.plot()
plt.imshow(img), plt.axis("off")
cv2.waitKey(0)
code doesn't give error but figure window is not opening
I think you are mixing cv2 and matplotlib. If you just want to display the image you can do it like so:
Using cv2:
import cv2
I = cv2.imread('path/to/img')
cv2.imshow('window_name', I)
cv2.waitKey(0)
or you can use matplotlib by simply adding plt.show() at the end as #JeruLuke pointed out. Just remember that OpenCV reads the image as BGR and this would make the colors show up weird when you display the image. You can use cv2.imread('path/to/image.jpg', COLOR_BGR2RGB) if you are set on using matplotlib.

Open high resolution images with Opencv

I can't open a 24MP pictures on Python with opencv. It only opens the upper left part apparently and not the full image. The kernel also stops after running the code.
Here's my code:
import cv2
import numpy as np
PICTURE_PATH_NAME = "IMG.JPG"
img = cv2.imread(PICTURE_PATH_NAME)
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
cv2.imshow("Gray Image", gray)
cv2.waitKey(0)
See the documentation for imshow as to how to get it to scale your image to fit the window at https://docs.opencv.org/4.1.1/d7/dfc/group__highgui.html#ga453d42fe4cb60e5723281a89973ee563
"If you need to show an image that is bigger than the screen
resolution, you will need to call namedWindow("", WINDOW_NORMAL)
before the imshow."

How do i get the original resolution of the image like it was when i open it normally outside python

I have changed the format of the images to png also..but of no use. Does cv2 / imshow decrease the resolution automatically?
import numpy as np
import cv2
from matplotlib import pyplot as plt
imgL = cv2.imread('image.png',0)
imgR = cv2.imread('2.png',0)
stereo = cv2.StereoBM_create(numDisparities=16, blockSize=15)
disparity = stereo.compute(imgR,imgL)
plt.imshow(disparity, 'gray')
plt.show()
My main aim is to generate the final image with the resolution as was the supplied images.
You're using imshow from matplotlib which might be the cause of different showing behaviour.
Instead try:
cv2.imshow("Res", disparity)
cv2.waitKey(0)
cv2.destroyAllWindows()
If that is still not good, please edit the question and include the resulting image and the input image.

Import image in python 3 with pillow

For a few hours now, I've been trying to figure out how to view an image I imported with pillow. So far, I got rid of all errors, but it just shows the exact filename of the photo, the image isn't showing up, please help me fix this.
This is what I have so far:
from PIL import Image
img = Image.open("image.jpg")
print(img)
From the docs the function to show an image is
Image.show(title=None, command=None)
So to display an image you can do
from PIL import Image
img = Image.open("image.jpg")
img.show()
Sir Please try this code
from PIL import Image
import matplotlib.pyplot as plt
%matplotlib inline
a=Image.open("F:\\FYP DATASET\\images\\train\\10_left.jpeg")
a
try by removing print statement and adding matplotlib library.
Purpose of %Matplotlib inline in Python:
By just writing variable without print statement will display the image in notebook and by img.show() It will display image in Photo Viewer (Windows photo viwer) etc depends on what you are using.
from PIL import Image
img = Image.open("man.png")
img.show()

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)
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')
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
I have written a short post to learn image reading with OpenCV in Python. You can see the below code snippet with the description.
import cv2 #Import openCV
import sys #import Sys. Sys will be used for reading from the command line. We give Image name parameter with extension when we will run python script
#Read the image. The first Command line argument is the image
image = cv2.imread(sys.argv[1]) #The function to read from an image into OpenCv is imread()
#imshow() is the function that displays the image on the screen.
#The first value is the title of the window, the second is the image file we have previously read.
cv2.imshow("OpenCV Image Reading", image)
cv2.waitKey(0) #is required so that the image doesn’t close immediately. It will Wait for a key press before closing the image.
To read an image with OpenCV you have to use the following synthax. If it doesn't work, there is a problem with the installation.
import cv2
image = cv2.imread('path_of_the_image.png')
cv2.imshow('img', image)
cv2.waitKey(0)
You didn't post the error it gives..
EDIT: I don't understand the negative points...for what ??
The reason for this error message is that cv2.imread() was unable to find the image where it was looking for the image. This should work if you add the full path to the image, like
img = cv2.imread('/home/foo/images/dumb.jpg',cv2.IMREAD_GRAYSCALE)
import cv2
import matplotlib.pyplot as plt
%matplotlib inline
# Hide grid lines
fig, ax = plt.subplots(figsize=(10,10))
ax.grid(False)
im=cv2.imread('./my_images.jpg')
plt.imshow(cv2.cvtColor(im, cv2.COLOR_BGR2RGB))
plt.show()
It use cv2.COLOR_BGR2RGB because it convert default settings of OpenCV which using BGR to RGB format
Use 0 rather than cv2.IMREAD_GRAYSCALE and I would hard code the location of the file rather than refer to it like that for example if it was on the C drive put 'C:\\Filename.jpg'
Try this one :
import cv2 as cv #openCV-3.4.1
import numpy as np
import matplotlib.pyplot as plt
img = cv.imread('image path and name .file type ',0)
cv.imshow('img',img)
cv.waitKey(0)
cv.destroyAllWindows()
It looks like your code is fine. The problem seems to be in the dimension of image that is being provided in the parameters. The error code says: size > 0 && width > 0. This condition is not meeting properly. Either dimension size or width is less than zero. You may want to check any other image and try with that.

Categories