Python import restarts other imports - python

I want to create a head tracking interface for a flight simulator. I'm going to use opencv for image acquisition and processing and use vjoy to emulate the joystick (which the flight simulator can pick up & recognise).
As part of developing a toolkit of routines I have a program which highlights the brightest & darkest points in a captured frame which works well.
import numpy as np
import pyvjoy #works if I comment this line out
import cv2
cap = cv2.VideoCapture(0)
#j = pyvjoy.VJoyDevice(1)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame - press q to exit',gray)
# vjoy lines commented out
# xAxis=xmin*4000
# j.data.wAxisX = 0x2000
# j.set_axis(HID_USAGE_X, xAxis)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
This code works if I comment out the import of the vjoy library. However, when I import vjoy it forces a reset of the shell even though there are no other active libraries or lines. How can I prevent this?

Related

How to make videocapture stream in a for loop to stram multiple cameras

I am trying to make this videocapture opencv2 python script allow me to do multiple video streams from my laptop cam and USB cams and I succeeded (with help of youtube) to do so only every time I add a camera I have to edit the line of code and add another videocapture line and another frame and another cv2.imshow. But I want to edit the video capture code in a way that allows me to stream as many cameras as detected without the need to add a line every time there is a camera using a loop. I'm obviously new here so accept my apologies if the solution is too simple.
This is the code that allows me to stream multiple cameras but with adding a line for each camera.
import urllib.request
import time
import numpy as np
import cv2
# Defining URL for camera
video_capture_0 = cv2.VideoCapture(0)
video_capture_1 = cv2.VideoCapture(1)
while True:
# Capture frame-by-frame
ret0, frame0 = video_capture_0.read()
ret1, frame1 = video_capture_1.read()
if (ret0):
# Display the resulting frame
cv2.imshow('Cam 0', frame0)
if (ret1):
# Display the resulting frame
cv2.imshow('Cam 1', frame1)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything is done, release the capture
video_capture_0.release()
video_capture_1.release()
cv2.destroyAllWindows()
I tried making a list camlist = [i for i in range(100)] and then adding that to a for loop that keeps adding it to videocapture. But I believe that's a mess so I deleted the code plus that doesn't seem so effective.
If you want to work with many cameras then first you should keep them on list - and then you can use for-loop to get all frame. And frames you should also keep on list so later you can use for-loop to display them. And finally you can use for-loop to release cameras
import cv2
#video_captures = [cv2.VideoCapture(x) for x in range(2)]
video_captures = [
cv2.VideoCapture(0),
#cv2.VideoCapture(1),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/krupowki-srodek/latest.mp4'),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/krakow4/latest.mp4'),
cv2.VideoCapture('https://imageserver.webcamera.pl/rec/warszawa/latest.mp4'),
]
while True:
results = []
for cap in video_captures:
ret, frame = cap.read()
results.append( [ret, frame] )
for number, (ret, frame) in enumerate(results):
if ret:
cv2.imshow(f'Cam {number}', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
for cap in video_captures:
cap.release()
cv2.destroyAllWindows()
And now if you even add new camera to list then you don't have to change rest of code.
But for many cameras it is good to run every camera in separated thread - but still keep all on lists.
Few days ago was question: How display multi videos with threading using tkinter in python?

I have this problem with opencv python on Macbook

My problem is when I try to run this code on my Mac, the camera turns on the green light but it doesn't open at all. I have no idea why this is happing. I tried a lot of things but nothing worked for me, I am just thinking the new update from Apple messed up some stuff, because it used to work before.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2BGRA)
# Display the resulting frame
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
In mac you have to use the Mac Terminal for the cv2 library since currently no other terminal to my knowledge asks for the camera permission.

OpenCV's VideoCapture malfunctioning when fed from IP Camera

I'm simply trying to read IP Camera live stream through OpenCV's simple code, i.e as follows:
import numpy as np
import cv2
src = 'rtsp://id:pass#xx.xx.xx.xx'
cap = cv2.VideoCapture(src)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
The problem here is, sometime it works like a charm by showing the running live video, but sometime else it creates a lot of blank windows which keeps popping up until the job is killed. Like the below image:
Why does it happen, also how can we avoid it?
Maybe you should cover the case that the video capture fails to establish a healthy stream.
Note that it is possible to not to receive a frame in some cases even though video capture opens. This can happen due to various reasons such as congested network traffic, insufficient computational resources, power saving mode of some IP cameras.
Therefore, I would suggest you to check in the frame size and make sure that your VideoCapture object is receiving the frame at right shape. (You can debug and see the size of a visible frame to learn the expected resolution of the camera.)
A change in your loop like following might help
min_expected_frame_size = [some integer]
while(cap.isOpened()):
ret, frame = cap.read()
width = cap.get(cv2.CAP_PROP_FRAME_WIDTH)
height = cap.get(cv2.CAP_PROP_FRAME_HEIGHT)
if ret==True and ((width*height) >= min_expected_frame_size):
cv2.imshow('frame',frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
else:
break

OpenCV & Python - Real time image (frame) processing

We're doing a project in school where we need to do basic image processing. Our goal is to use every video frame for the Raspberry Pi and do real time image processing.
We've tried to include raspistill in our python-program but so far nothing has worked. The goal of our project is to design a RC-car which follows a blue/red/whatever coloured line with help from image processing.
We thought it would be a good idea to make a python-program which does all image processing necessary, but we currently struggle with the idea of bringing recorded images into the python program. Is there a way to do this with picamera or should we try a different way?
For anyone curious, this is how our program currently looks
while True:
#camera = picamera.PiCamera()
#camera.capture('image1.jpg')
img = cv2.imread('image1.jpg')
width = img.shape[1]
height = img.shape[0]
height=height-1
for x in range (0,width):
if x>=0 and x<(width//2):
blue = img.item(height,x,0)
green = img.item(height,x,1)
red = img.item(height,x,2)
if red>green and red>blue:
OpenCV already contains functions to process live camera data.
This OpenCV documentation provides a simple example:
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
Of course, you do not want to show the image but all your processing can be done there.
Remember to sleep a few hundred milliseconds so the pi does not overheat that much.
Edit:
"how exactly would I go about it though. I used "img = cv2.imread('image1.jpg')" all the time. What do I need to use instead to get the "img" variable right here? What do I use? And what is ret, for? :)"
ret indicates whether the read was successful. Exit program if not.
The read frame is nothing other than your img = cv2.imread('image1.jpg') so your detection code should work exactly the same.
The only difference is that your image does not need to be saved and reopened. Also for debugging purposes you can save the recorded image, like:
import cv2, time
cap = cv2.VideoCapture(0)
ret, frame = cap.read()
if ret:
cv2.imwrite(time.strftime("%Y%m%d-%H%M%S"), frame)
cap.release()
You can use picamera to acquire images.
To make it "real time", you can acquire data each X milliseconds. You need to set X depending on the power of your hardware (and the complexity of the openCV algorithm).
Here's an example (from http://picamera.readthedocs.io/en/release-1.10/api_camera.html#picamera.camera.PiCamera.capture_continuous) how to acquire 60 images per second using picamera:
import time
import picamera
with picamera.PiCamera() as camera:
camera.start_preview()
try:
for i, filename in enumerate(camera.capture_continuous('image{counter:02d}.jpg')):
print(filename)
time.sleep(1)
if i == 59:
break
finally:
camera.stop_preview()

OpenCV: Face detection taking advantage of a command line

I run this (first one) example that launches the webcam of my latop so that I can see myself on the screen.
import numpy as np
import cv2
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()
I installed OpenBr on Ubuntu 14.04 LTS and I run successfully this command on a picture of myself:
br - gui -algorithm ShowFaceDetection -enrollAll -enroll /home/nakkini/Desktop/myself.png
The above command I run on the Terminal displays my picture and draws a square around my face (face detection), it also highlights my eyes in green.
My Dream:
I wonder if there is a way to combine this command with the short program above so that when the webcam is launched I can see my face surrounded by the green rectangle ?
Why do I need this ?
I found similar programs in pure OpenCV/Python for this purpos. However, for later needs, I need more things than the simple face detection and I judge by myself that OpenBR will save me lot of headache. That is why I am looking for a way to run the command line somewhere inside the code above as a first but big step.
Hints:
The frame in the code corresponds to myself.png of the command line. The solution to be found will try to pass frame in the place of myself.png to the command line within the program itself.
Thank you very much in advance.
EDIT:
After correcting the typos of #Xavier's solution I have no errors. However the program does not run as I want it:
First, the camer is launched and I see myself but my face is not detected with a green rectangle. Secondly, I press any key to exit but the program does not exit: it shows me a picture of myself with my face detected. A last key press exists the program. My goal is to see my face detected during the camera functionment.
you do not need openbr for this at all.
just see opencv's python face-detect tutorial
something like this should work
import numpy as np
import cv2
import os
cap = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = cap.read()
# Our operations on the frame come here
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
# Display the resulting frame
cv2.imshow('frame',gray)
if cv2.waitKey(1) & 0xFF == ord('q'):
cv2.imwrite( "/home/nakkini/Desktop/myself.png", gray );
os.system('br - gui -algorithm -ShowFaceDetection -enrollAll -enroll /home/nakkini/Desktop/myself.png')
break
# When everything done, release the capture
cap.release()
cv2.destroyAllWindows()

Categories