imshow() function is not giving output as expected in python - python

import cv2
img=cv2.imread('test.jpg')
cv2.imshow("frame1",img)
waitKey(0)
input_image
output_image
Above is my code and it is not giving expected result(complete image). Roughly 10% of image is getting as output.
My input image is of size 1.24MB.is there any size limitations in opencv??
Thanks for help in advance

The problem is arising from cv2.imshow() function. As you are using cv2 from python, the command to use would be cv2.namedWindow('image',cv2.WINDOW_NORMAL) before cv2.imshow(). This should solve your problem. I tried your code the following way and it worked for me.
import cv2
img=cv2.imread('input1.jpg')
cv2.namedWindow('image',cv2.WINDOW_NORMAL)
#cv2.resizeWindow('image', 600,600)
cv2.imshow("image",img)
k = cv2.waitKey(0)
if k == 27:
cv2.imwrite('newImage2.png', img)
cv2.destroyAllWindows()
See if this can solve your problem.

You can use the namedwindow() method to adjust the screen size to fit the image size.
Here is the function;
cv.NamedWindow(name, flags=CV_WINDOW_AUTOSIZE)

Related

Input while cv2 shows an image

I would like to get input when I am showing an image using OpenCV's imshow() function. But If I do so, the image doesn't show correctly and a grey image appears instead.
It works if I use destroyAllWindows() command, but is there a proper solution for this?
def write_solution(crop):
cv2.imshow('Frage',crop)
ans = input("Antwort: ")
cv2.waitKey(0)
cv2.destroyAllWindows()
return ans

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.

(scikit-image) HOG visualization image appears black when saved

I am new to computer vision and image processing and am using this code
from skimage.feature import hog
hog_list, hog_img = hog(test_img_gray,
orientations=8,
pixels_per_cell=(16, 16), cells_per_block=(1, 1),
block_norm='L1',
visualise=True,
feature_vector=True)
plt.figure(figsize=(15,10))
plt.imshow(hog_img)
to get this HOG visualization image
I have 2 questions at this point:
When I try to save this image (as a .pdf or .jpg) the resulting image is pure black. Converting this image to PIL format and examining it with
hog_img_pil = Image.fromarray(hog_img)
hog_img_pil.show()
still shows the image as pure black. Why is this happening and how can I fix it?
When I try to run this code
hog_img = cv2.cvtColor(hog_img, cv2.COLOR_BGR2GRAY)
to convert the image to grayscale I get the error error: (-215) depth == CV_8U || depth == CV_16U || depth == CV_32F in function cvtColor. What do I need to do to get this image in grayscale and why would this be happening?
As additional information, running hog_img.shape returns (1632, 1224) which is just the size of the image, which I had initially interpreted to mean that the image is already is already in grayscale (since it appears to be lacking a dimension for color channel). However, when I then tried to run
test_img_bw = cv2.adaptiveThreshold(
src=hog_img,
maxValue=255,
adaptiveMethod=cv2.ADAPTIVE_THRESH_GAUSSIAN_C,
thresholdType=cv2.THRESH_BINARY,
blockSize=115, C=4)
I got the error error: (-215) src.type() == CV_8UC1 in function adaptiveThreshold which this answer seems to indicate means that the image is not in grayscale.
Finally, another bit of useful information is that running print(hog_img.dtype) on the image returns float64.
I will continue to debug, in the meantime
Thanks for any thoughts :)
Inverting the image with hog_img_inv = cv2.bitwise_not(hog_img) and using
plt.figure(figsize=(15,10))
plt.imshow(hog_img_uint8_inv)
showed that the lines were in fact there but are very faint (I've included the image here for comletness, but you can barley see it (but trust me, it's there)). I will have to do some more processing of the image to get the lines more distinguishable.
Running print(hog_img.dtype) showed that the dtype was float64 when (I think) it should have been uint8. I fixed this by running hog_img_uint8 = hog_img.astype(np.uint8) which seems to have fixed the problem with passing the image to other algorithms (eg. cv2.adaptiveThreshold).
If had the same problem. But if you look inside the docu, they also use this code for better visualisation:
# Rescale histogram for better display
hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 0.02))
But I still have the same problem. Visualisation with matplotlib is no problem. saving the image with opencv (or skimage) saves only a black image...

Extract foreground from individual frames using opencv for python

The problem
I'm working with a camera that posts a snapshot to the web every 5 seconds or so. The camera is monitoring a line of people. I'd like my script to be able to tell me how long the line of people is.
What I've tried
At first, I thought I could do this using BackgroundSubtractorMOG, but this is just producing a black image. Here's my code for that, modified to use an image instead of a video capture:
import numpy as np
import cv2
frame = cv2.imread('sample.jpg')
fgbg = cv2.BackgroundSubtractorMOG()
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
cv2.waitKey()
Next, I looked at foreground extraction on an image, but this is interactive and doesn't suit my use case of needing the script to tell me how long the line of people is.
I also tried to use peopledetect.py, but since the image of the line is from an elevated position, that script doesn't detect any people.
I'm brand new to opencv, so any help is greatly appreciated. I can supply any additional details upon request.
Note:
I'm not so much looking for someone to solve the overall problem, as I am just trying to figure out a way to separate out the people from the background. However, I am open to approaching the problem a different way if you think you have a better solution.
EDIT: Here's a sample image as requested:
I figured it out! #QED helped me get there. Basically, you can't do this with just one image. You need AT LEAST 2 frames to compare so the algorithm can tell what's different (foreground) and what's the same (background). So I took 2 frames and looped through them to "train" the algorithm. Here's my code:
import numpy as np
import cv2
i = 1
while(1):
fgbg = cv2.BackgroundSubtractorMOG()
while(i < 3):
print 'img' + `i` + '.jpg'
frame = cv2.imread('img' + `i` + '.jpg')
fgmask = fgbg.apply(frame)
cv2.imshow('frame', fgmask)
i += 1
k = cv2.waitKey(30) & 0xff
if k == 27:
break
cv2.destroyAllWindows()
And here's the result from 2 consecutive images!

resizing a picture in opencv?

i am writing a face dection program in opencv. And this is the error code below:
result = img[rects[0]:rects[1], rects[2]:rects[3]]
result = cv2.resize(result, (100,100))
img is our original picture and the first step is croping out our rigion of interest into result.
The second step is resize to 100*100 pixels.
the error is:
result = cv2.resize(result, (100,100))
error: ..\..\..\src\opencv\modules\imgproc\src\imgwarp.cpp:1725: error: (-215) ssize.area() > 0
Hope someone can help me. Thanks a lot.
Had the same error in python ,found that image was empty so check whether imread worked or not by using imshow or checking it for NULL then use cv2.resize .

Categories