CV2 image and webcam always minimized when running a program - python

cap = cv2.VideoCapture(0)
and
img = cv2.imread(/users/..../jumpingjacks.jpeg, 1)
cv2.imshow('Jumping Jacks', img)
when my prog run these two codes, the webcam feed and image doesn't pop out, but instead, it shows as minimized version, which requires me to press the icon at the bottom of the screen to bring it forward. anyidea what caused this ?

Found the answer by trying out this code:
img = cv2.imread('/users/..../jumpingjacks.jpeg', 1)
cv2.imshow('Jumping Jacks', img)
cv2.setWindowProperty("Jumping Jacks", cv2.WND_PROP_TOPMOST, 1)
cv2.waitKey(5000)
cv2.destroyAllWindows()

Related

Python OpenCV images get blurry after successive shots

I'm new to Open CV and python, and I've been facing a problem:
I've been doing a project on my Raspberry Pi where the webcam takes a grey scale image, removes the background, and saves it in a folder.
This is used by a machine learning algorithm to detect the object in the image.
The webcam is fixed at a particular point so I first take an image of the background and then take a picture of the object. The background is then removed from the object and it looks fine.
But if I repeat the process and overwrite the image, it becomes blurred.
This effect keeps happening until after about three or four shots the image becomes blurry and my program cant identify the object in it.
My code is:
#get Background
import cv2
cam = cv2.videoCapture(0)
ret, frame = cam.read()
if ret:
img_name = '/home/pi/Desktop/background.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
print('{} written'.format(img_name))
cam.release()
#takeImage
import cv2
import numpy as np
ret, frame = cam.read()
back = cv2.imread('/home/pi/Desktop/background.png')
if ret:
img_name = '/home/pi/Desktop/img_capture.png'
grey_img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imwrite(img_name, grey_img)
grey_obj = cv2.subtract(cv2.imread(img_name), back)
cv2.imwrite(img_name, grey_obj)
print('{} written'.format(img_name))
cam.release()
I'm using a Logitech webcam but I'm not sure of the exact model
Please help me out, and thanks in advance.
Clear at the start:
Not so much:
Not at all:

cv2.imshow image window placement is outside of viewable screen

I am running Anaconda install of python35 with cv2 install from menpo.
I am having trouble with cv2.imshow() inconsistently placing the image window outside of the viewable screen when running code similar to the one below both as a standalone script and line by line in the console (cmd, spyder, ipython)...
import cv2
img = cv2.imread('Image71.jpg',0)
cv2.startWindowThread()
cv2.namedWindow('image')
cv2.imshow('image',img)
cv2.waitKey(0)
cv2.destroyAllWindows()
I have also tried the above without cv2.starWindowThread() and cv2.namedWindow() with the same result. The window appears on my taskbar but is not in view, cv2.waitKey(0) responds to the keystroke, and I am not able to bring the window into view using any of the window arrangement shortcut keys for Windows 10 (e.g. alt+tab, Winkey + left, etc).
My OS is Win10 version 1709.
Any help is much appreciated, thx!
img = cv2.imread("test.png")
winname = "Test"
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, 40,30) # Move it to (40,30)
cv2.imshow(winname, img)
cv2.waitKey()
cv2.destroyAllWindows()
wrapped answer by Kinght in a function for easy calling
def showInMovedWindow(winname, img, x, y):
cv2.namedWindow(winname) # Create a named window
cv2.moveWindow(winname, x, y) # Move it to (x,y)
cv2.imshow(winname,img)
img = cv2.imread('path.png')
showInMovedWindow('named_window',img, 0, 200)

Weird Error in OpenCV

I'm writing a program in python using OpenCV which detects the edges (Canny Edge Detector) from the footage my webcam records. I'm also using two track-bars in order to control the threshold values (in order for to understand how these values change the output of this edge detector).
The code I wrote is the following:
import cv2
import numpy as np
def nothing(x):
pass
img = np.zeros((300,512,3), np.uint8)
cv2.namedWindow('cannyEdge')
cv2.createTrackbar("minVal", "cannyEdge", 0,100, nothing)
cv2.createTrackbar("maxVal", "cannyEdge", 100,200,nothing)
cap = cv2.VideoCapture(0)
while(True):
minVal = cv2.getTrackbarPos("minVal", "cannyEdge")
maxVal = cv2.getTrackbarPos("maxVal", "cannyEdge")
#capture frame by frame
ret, frame = cap.read()
cv2.imshow('frame', frame)
edge = cv2.Canny(frame,minVal,maxVal)
#display the resulting frame
cv2.imshow('frame', edge)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
#When everything is done, release the capture
cap.release
cv2.destroyAllWindows()
This program is for educational purposes only as I'm currently learning to use OpenCV.
Every time I run the program above the code seems to be working just fine but I get the following Error:
GLib-GObject-CRITICAL **: g_object_unref: assertion 'G_IS_OBJECT (object)' failed
I've searched for the reason this error occurs but I haven't found anything helpful. My instinct tells me that my implementation for the trackbars is wrong and thus it's causing this error.
The tutorials I used are the following:
OpenCV tutorials - Canny Edge Detector
OpenCV tutorials - Trackbars
Does anybody know why this error occurs? Any help will be appreciated!
I am running Ubuntu 14.04, OpenCV 3.2.0 and Python 2.7.6
Try making the track bars and displaying the image in the same window and see if the error persists. I bet it shouldn't. Change: cv2.imshow('cannyEdge', edge)
Have you created another window named "frame"? If not, it looks like you should change 'frame' to 'cannyEdge':
cv2.imshow('cannyEdge', frame)

OpenCV's waitKey() alternative in IPython Notebook

I'm trying to show images with cv2 library in my Jupiter Notebook with cv2.imshow(img) and it shows as expected, but I can not use or don't know how to use cv2.waitKey(0), hence the cell will not stop executing.
cv2.waitKey(0) works in script, but not in Notebook.
Here's a snippet:
cv2.imshow('Image', img)
cv2.waitKey(0)
cv2.destroyAllWindows()
How do I stop executing cell without restarting the whole kernel?
So, thanks to #Micka, here's the solution:
You must write cv2.startWindowThread() first, explained here.
I found the answer from primoz very useful. Here is a code for a function that reads an image from specified path, draws the image, waits for any input to close a window and returns the image object.
import cv2
def cv2_imshow(path, title):
"""
function:
- reads image from `path`,
- shows image in a separate window,
- waits for any key to close the window.
return: image object
"""
img = cv2.imread(path)
cv2.startWindowThread()
cv2.imshow(title, img)
cv2.waitKey(0)
cv2.destroyAllWindows()
return img
Call the function with image path and title:
img_raw = cv2_imshow(path = r'img\example\test.png', title = "raw image")
I have just developed a library to facilitate the opencv functionality in Jupyter.
I used buttons in jupyter for simulating waitKey
It shows the image in the jupyer.
Document
Installation
pip install opencv_jupyter_ui
Usage
You need to only change cv2 to jcv2.
import opencv_jupyter_ui as jcv2
...
jcv2.imshow(img,title)
if jcv2.waitKey(1000)==ord('q'):
break
jcv2.destroyAllWindows()

Why are webcam images taken with Python so dark?

I've showed in various ways how to take images with a webcam in Python (see How can I take camera images with Python?). You can see that the images taken with Python are considerably darker than images taken with JavaScript. What is wrong?
Image example
The image on the left was taken with http://martin-thoma.com/html5/webcam/, the one on the right with the following Python code. Both were taken with the same (controlled) lightning situation (it was dark outside and I only had some electrical lights on) and the same webcam.
Code example
import cv2
camera_port = 0
camera = cv2.VideoCapture(camera_port)
return_value, image = camera.read()
cv2.imwrite("opencv.png", image)
del(camera) # so that others can use the camera as soon as possible
Question
Why is the image taken with Python image considerably darker than the one taken with JavaScript and how do I fix it?
(Getting a similar image quality; simply making it brighter will probably not fix it.)
Note to the "how do I fix it": It does not need to be opencv. If you know a possibility to take webcam images with Python with another package (or without a package) that is also ok.
Faced the same problem. I tried this and it works.
import cv2
camera_port = 0
ramp_frames = 30
camera = cv2.VideoCapture(camera_port)
def get_image():
retval, im = camera.read()
return im
for i in xrange(ramp_frames):
temp = camera.read()
camera_capture = get_image()
filename = "image.jpg"
cv2.imwrite(filename,camera_capture)
del(camera)
I think it's about adjusting the camera to light. The former
former and later images
I think that you have to wait for the camera to be ready.
This code works for me:
from SimpleCV import Camera
import time
cam = Camera()
time.sleep(3)
img = cam.getImage()
img.save("simplecv.png")
I took the idea from this answer and this is the most convincing explanation I found:
The first few frames are dark on some devices because it's the first
frame after initializing the camera and it may be required to pull a
few frames so that the camera has time to adjust brightness
automatically.
reference
So IMHO in order to be sure about the quality of the image, regardless of the programming language, at the startup of a camera device is necessary to wait a few seconds and/or discard a few frames before taking an image.
Tidying up Keerthana's answer results in my code looking like this
import cv2
import time
def main():
capture = capture_write()
def capture_write(filename="image.jpeg", port=0, ramp_frames=30, x=1280, y=720):
camera = cv2.VideoCapture(port)
# Set Resolution
camera.set(3, x)
camera.set(4, y)
# Adjust camera lighting
for i in range(ramp_frames):
temp = camera.read()
retval, im = camera.read()
cv2.imwrite(filename,im)
del(camera)
return True
if __name__ == '__main__':
main()

Categories

Resources