my function did not return continuous frame ,it return only signal frame and then break
here is my code:
import cv2
import numpy as np
def video():
cam=cv2.VideoCapture(0)
while cam.isOpened:
_,frame=cam.read()
return frame
im=video()
cv2.imshow("image",im)
cv2.waitKey(0)
I want such function ,when i call this function ,anywhere in my code it return a continues frame and i do stuff on it whatever display ,face detection or other stuff
Try to gather the frames in a while loop without breaking it by returning:
import cv2
import numpy as np
def video(cam):
_,frame=cam.read()
return frame
cam=cv2.VideoCapture(0)
while cam.isOpened:
im=video(cam)
cv2.imshow("image",im)
cv2.waitKey(0)
When you return, you just exit the while loop, so it just shows 1 image.
import cv2
import numpy as np
cam=cv2.VideoCapture(0)
while cam.isOpened:
_,frame=cam.read()
cv2.imshow("image",frame)
key = cv2.waitKey(1) & 0xFF
if key == ord("q"):
break
cap.release()
cv2.destroyAllWindows()
Related
I would like to gain out the arrays of object detected using python and YOLOv5. I use:
import torch
import cv2
from matplotlib import pyplot as plt
import numpy as np
import uuid
import os
import time
model = torch.hub.load('ultralytics/yolov5', 'custom', path="C:\\Users\\Legion\\Desktop\\yolo\\yolov5\\runs\\train\\exp5\\weights\\last.pt", force_reload=True)
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
results = model(frame)
cv2.imshow('YOLO', np.squeeze(results.render()))
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
How to get the arrays of objects detected and how to get them as integers, to provide comparison? F.e. If arrays [x,y] < [70,90] then ...
Thank you guys.
I have searched a lot and now I need specific idea how to get the results I need.
I am relatively new to python and to openCV, I am trying to create a program that grabs input from my Macs' webcam and displays it in a window, and ultimately can process and edit these frames. Here is my code:
import cv2
import numpy as nmp
capture=cv2.VideoCapture(0)
while True:
frame = capture.read()
cv2.imshow("Webcam", frame)
if (cv2.waitKey(0)):
break
cv2.release()
cv2.destroyAllWindows()
my light near my webcam turns on but then the program stops with the following error
Traceback (most recent call last):
File "/Users/spinder/Desktop/WebCam.py", line 7, in <module>
cv2.imshow("Webcam", frame)
TypeError: mat is not a numerical tuple
there are similar questions in here but they do not fix my problem, any advice, fix or workaround would be greatly appreciated.
According to the docs:
Python: cv2.VideoCapture.read([image]) → retval, image
This returns 2 values, the first indicates if the frame is obtained correctly and the second is the frame. So in your case the code should be as follows:
import cv2
import numpy as nmp
capture=cv2.VideoCapture(0)
while True:
res, frame = capture.read()
if res:
cv2.imshow("Webcam", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
capture.release()
cv2.destroyAllWindows()
I'm trying to use MOG background subtraction but the "history" function doesn't seem to work.
OpenCV 2.4.13
Python (2.7.6)
Observation: The program appears to use the very first frame it captures for all future background subtractions.
Expectation: The background should slowly evolve based on the "history" parameter, so that if the camera angle changes, or if a person/object leaves the field-of-view, the "background" image will change accordingly.
import cv2
import numpy as np
cap = cv2.VideoCapture(0)
mog = cv2.BackgroundSubtractorMOG(history=10, nmixtures=5, backgroundRatio=0.25)
while True:
ret, img1 = cap.read()
if ret is True:
cv2.imshow("original", img1)
img_mog = mog.apply(img1)
cv2.imshow("mog", img_mog)
if cv2.waitKey(10) & 0xFF == ord(q):
break
video_capture.release()
cv2.destroyAllWindows()
Thank you in advance for your help!
I created a white colored image matrix using numpy and now i want to blink any color over the right half of the image matrix that i created i am using the following code but it's not working as expected
import numpy as np
import cv2
import time
i=0
img=np.zeros((400,800,3),np.uint8)
img.fill(255)
while(i<=1):
img[0:400,400:800]=(153,0,255)
cv2.imshow('package',img)
time.sleep(5)
img[0:400,400:800]=(255,255,255)
cv2.imshow('package',img)
time.sleep(5)
img[0:400,400:800]=(153,0,255)
cv2.imshow('package',img)
i=i+1
cv2.waitKey(0)
cv2.destroyAllWindows()
`
You need "waitkey" just after imshow to ensure image redraws. waitkey(5000) means 5 seconds wait. "time.sleep(5)" is not necessary here:
import numpy as np
import cv2
import time
i=0
img=np.zeros((400,800,3),np.uint8)
img.fill(255)
while(i<=1):
img[0:400,400:800]=(153,0,255)
cv2.imshow('package',img)
cv2.waitKey(5000)
img[0:400,400:800]=(255,255,255)
cv2.imshow('package',img)
cv2.waitKey(5000)
img[0:400,400:800]=(153,0,255)
cv2.imshow('package',img)
cv2.waitKey(5000)
i=i+1
cv2.destroyAllWindows()
I am reading a video frame by frame using:
vc = cv2.VideoCapture('test.avi')
and later on I check whether the frame has been read using:
if vc.isOpened():
rval,frame = vc.read()
else:
rval = False
Now the problem is , if I try to convert this frame to a numpy array using the following code:
PILImage = Image.fromstring("L",cv.GetSize(frame),frame.tostring())
NumPyArray = np.array(PILImage)
I get an error saying:
CvArr argument 'arr' must be IplImage, CvMat or CvMatND. Use fromarray() to convert numpy arrays to CvMat or cvMatND
From Documentation of VideoCapture::read I found that it returns two things [retVal,Image] . How do I get the Image part only and how do I convert it to Numpy Array?
Further Info:
Basically the whole point in doing this is that ,I am trying to write a program which allows me to go through each frame of the video by pressing spacebar, and select a particular region from any frame and save it as a jpg. Here is the Code:
from ITMS import ITMS
import cv2
from cv2 import cv
import numpy as np
import matplotlib.pyplot as plt
import Image
import matplotlib.widgets as widgets
def onselect(eclick, erelease):
if eclick.ydata>erelease.ydata:
eclick.ydata,erelease.ydata=erelease.ydata,eclick.ydata
if eclick.xdata>erelease.xdata:
eclick.xdata,erelease.xdata=erelease.xdata,eclick.xdata
ax.set_ylim(erelease.ydata,eclick.ydata)
ax.set_xlim(eclick.xdata,erelease.xdata)
fig.canvas.draw()
def subImager(arr):
fig = plt.figure()
ax = fig.add_subplot(111)
plt_image=plt.imshow(arr,cmap="Greys_r")
rs=widgets.RectangleSelector(
ax, onselect, drawtype='box',
rectprops = dict(facecolor='red', edgecolor = 'red', alpha=0.2, fill=True))
plt.show()
cv2.namedWindow("preview")
vc = cv2.VideoCapture('test.avi')
if vc.isOpened():
rval,frame = vc.read()
else:
rval = False
while rval:
key = cv2.waitKey(30)
if key==32:
cv2.imshow("preview", frame)
NumPyArray=ITMS.CVtoNPArray(frame)
subImager(NumPyArray)
rval,frame = vc.read()
elif key==27:
break
cv2.destroyAllWindows()
ITMS Class:
from cv2 import cv
import cv2
import numpy as np
from PIL import Image
class ITMS:
def __init__(self):
pass
def CVtoNPArray(CVImage):
PILImage = Image.fromstring("L",cv.GetSize(CVImage),CVImage.tostring())
NumPyArray = np.array(PILImage)
return NumPyArray
CVtoNPArray=staticmethod(CVtoNPArray)
You are over-complicating things, the image returned in your frame name is already a numpy array. If you want to convert it to PIL, simply do Image.fromarray(frame).