I don't know anything about Python, but I have a job that requires processing, so I need to implement some functions.
Below is my code.
When I ran Python,
Traceback (most recent call last): File "C:\Users\user\Desktop\bodypix\bodypix.py", line 80, in
frame.shape
NameError: name 'frame' is not defined
This error is checked.
Why does this error appear?
If you know how to solve this problem, I would really appreciate your help.
import tensorflow as tf
from tf_bodypix.api import download_model, load_model, BodyPixModelPaths
import cv2
from matplotlib import pyplot as plt
import numpy as np
# # 2. Detections
# In[2]:
load_model(download_model(BodyPixModelPaths.MOBILENET_FLOAT_50_STRIDE_16))
# In[3]:
bodypix_model = load_model(download_model(BodyPixModelPaths.MOBILENET_FLOAT_50_STRIDE_16))
# In[27]:
# get vid cap device
cap = cv2.VideoCapture(0)
# loop through frame
while cap.isOpened():
ret, frame = cap.read()
# BodyPix Detections
result = bodypix_model.predict_single(frame)
mask = result.get_mask(threshold=0.5).numpy().astype(np.uint8)
masked_image = cv2.bitwise_and(frame, frame, mask=mask)
# Show result to user on desktop
cv2.imshow('BodyPix', masked_image)
# Break loop outcome
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release() # Releases webcam or capture device
cv2.destroyAllWindows() # Closes imshow frames
# # 3. Add Virtual Background
# In[12]:
img = cv2.imread('beach.jpg')
img = img[:480, :640, :]
# In[13]:
plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
# In[14]:
img.shape
# In[15]:
frame.shape
# In[24]:
plt.imshow(mask)
# In[23]:
plt.imshow(np.where(np.add(mask, -1) == -1, 1, np.add(mask, -1)))
# In[ ]:
# get vid cap device
cap = cv2.VideoCapture(0)
# loop through frame
while cap.isOpened():
ret, frame = cap.read()
# BodyPix Detections
result = bodypix_model.predict_single(frame)
mask = result.get_mask(threshold=0.5).numpy().astype(np.uint8)
masked_image = cv2.bitwise_and(frame, frame, mask=mask)
# Apply virtual background
neg = np.add(mask, -1)
inverse = np.where(neg==-1, 1, neg).astype(np.uint8)
masked_background = cv2.bitwise_and(img, img, mask=inverse)
final = cv2.add(masked_image, masked_background)
# Show result to user on desktop
cv2.imshow('BodyPix', final)
# Break loop outcome
if cv2.waitKey(10) & 0xFF == ord('q'):
break
cap.release() # Releases webcam or capture device
cv2.destroyAllWindows() # Closes imshow frames
You're referencing frame.shape prior to frame being assigned. Notice how img.shape is allowed since before this there is an assignment: img = cv2.imread('beach.jpg').
Read the documentation to see what "frame" should be assigned to.
Related
happy day, I am trying to synchronize two cameras
(my local computer) and the camera of my cell phone with IP Web cam,
however when running the code it generates an error and the two
cameras that I have previously opened are closed (see photo ). What
would this be due to? Thanks for your help!
ERROR -->
Traceback (most recent call last):
File "C:\Users\JUCABALL\Desktop\camera_stream_openCV-master\main.py", line 20, in <module>
cv2.imshow ('cam1', frame1)
cv2.error: OpenCV (4.5.4-dev) D:\a\opencv-python\opencv-python\opencv\modules\imgproc\src\color.cpp: 182:
error: (-215: Assertion failed)! _src .empty () in function 'cv :: cvtColor'
This is the tabs - after fews seconds tabs close
[Tabs, 2 cameras][1]
This is my code
import numpy as np
import cv2
# capture the webcam
vid1 = cv2.VideoCapture(0, cv2.CAP_DSHOW)
vid2 = cv2.VideoCapture(1, cv2.CAP_DSHOW)
vid3 = cv2.VideoCapture(
"http://192.168.0.11:8080/video", cv2.CAP_DSHOW
) # ipwebcam address
while True: # while true, read the camera
ret, frame = vid1.read()
ret1, frame1 = vid2.read()
ret2, frame2 = vid3.read()
if ret:
cv2.imshow("cam0", frame) # frame with name and variable of the camera
cv2.imshow("cam1", frame1)
cv2.imshow("cam3", frame2)
# to break the loop and terminate the program
if cv2.waitKey(1) & 0xFF == ord("q"):
break
vid1.release()
vid2.release()
vid3.release()
The problem is you're not checking the value of ret1 and ret2.
If those are False, the images will not have been captured, and you're still trying to show them, and OpenCV crashes because there's no way to show an image that doesn't exist.
Try
if ret:
cv2.imshow("cam0", frame)
if ret1:
cv2.imshow("cam1", frame1)
if ret2:
cv2.imshow("cam3", frame2)
instead.
You could also store all of the capture devices in a list, and all the captured images equally so, to make the code a little simpler to work with:
import numpy as np
import cv2
captures = [
cv2.VideoCapture(0, cv2.CAP_DSHOW),
cv2.VideoCapture(1, cv2.CAP_DSHOW),
cv2.VideoCapture("http://192.168.0.11:8080/video", cv2.CAP_DSHOW), # ipwebcam address
]
while True: # while true, read the camera
frames = []
for cap in captures:
ret, frame = cap.read()
frames.append((frame if ret else None))
for i, frame in enumerate(frames):
if frame is not None: # None if not captured
cv2.imshow(f"cam{i}", frame)
# to break the loop and terminate the program
if cv2.waitKey(1) & 0xFF == ord("q"):
break
for cap in captures:
cap.release()
I am trying to use mediapipe to track hands. I am using Python 3.7.9 on Windows 10, my code is below:
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
cap = cv2.VideoCapture(0)
while (True):
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
results = mp_hands.Hands.process(imgRGB)
print(result)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
I'm getting this error:
Traceback (most recent call last):
File "C:/Users/Tomáš/PycharmProjects/pythonProject/hand_detect.py", line 11, in <module>
results = mp_hands.Hands.process(imgRGB)
TypeError: process() missing 1 required positional argument: 'image'
[ WARN:1] global D:\a\opencv-python\opencv-python\opencv\modules\videoio\src\cap_msmf.cpp (438) `anonymous-namespace'::SourceReaderCB::~SourceReaderCB terminating async callback
Error says that I need to pass one more argument 'self' before I pass argument 'image'. I've been browsing a lot and every related code doesnt use first argument in the process() function. Could anyone help me solve this error?
The problem is that you do not create an object of mp_hands.Hands before you want to process it. The following code solves it and prints some results. By the way, this was well documentated in the documentation link i commented before.. :
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_hands = mp.solutions.hands
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW) # i had problems before reading webcam feeds, so i added cv2.CAP_DSHOW here
while True:
success, img = cap.read()
imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
# you have to create an object of mp_hands.Hands to get results
# alternatively you could do: results = mp_hands.Hands().process(imgRGB)
with mp_hands.Hands() as hands:
results = hands.process(imgRGB)
# continue loop if no results were found
if not results.multi_hand_landmarks:
continue
# print some results
for hand_landmarks in results.multi_hand_landmarks:
print(
f'Index finger tip coordinates: (',
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].x}, '
f'{hand_landmarks.landmark[mp_hands.HandLandmark.INDEX_FINGER_TIP].y})'
)
if cv2.waitKey(10) & 0xFF == ord('q'):
break
Edit:
This is more or less the same code from here:
import cv2
import mediapipe as mp
mp_drawing = mp.solutions.drawing_utils
mp_drawing_styles = mp.solutions.drawing_styles
mp_hands = mp.solutions.hands
# initialize webcam
cap = cv2.VideoCapture(0, cv2.CAP_DSHOW)
with mp_hands.Hands(model_complexity=0,
min_detection_confidence=0.5,
min_tracking_confidence=0.5) as hands:
while cap.isOpened():
success, image = cap.read()
if not success:
print("Ignoring empty camera frame.")
# If loading a video, use 'break' instead of 'continue'.
continue
# To improve performance, optionally mark the image as not writeable to
# pass by reference.
image.flags.writeable = False
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
results = hands.process(image)
# Draw the hand annotations on the image.
image.flags.writeable = True
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)
if results.multi_hand_landmarks:
for hand_landmarks in results.multi_hand_landmarks:
mp_drawing.draw_landmarks(
image,
hand_landmarks,
mp_hands.HAND_CONNECTIONS,
mp_drawing_styles.get_default_hand_landmarks_style(),
mp_drawing_styles.get_default_hand_connections_style())
# Flip the image horizontally for a selfie-view display.
cv2.imshow('MediaPipe Hands', cv2.flip(image, 1))
if cv2.waitKey(5) & 0xFF == 27:
break
cap.release()
The task is, i take pictures from the camera, and i process pictures using cnns, and then display the pic with the result. But there is an error when i use opencv python interface to show the image(the os is the mac os):
while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imread('hello.jpg')
h, w, _ = frame.shape
img = copy.deepcopy(frame)
img = pre_process(img)
test_data.append([img])
ret_res = _infer(inferer, test_data, threshold)
draw_result(frame, ret_res, h, w)
cv2.imshow("hellocapture", frame)
the following error occurred:
PC: # 0x0 (unknown)
*** SIGFPE (#0x7fffc5186d01) received by PID 36436 (TID 0x7fffe38773c0) stack
trace: ***
# 0x7fffdab7bb3a _sigtramp
# 0x7fffc5186d02 CFNumberCreate
# 0x7fffc6c027b5 -[NSPlaceholderNumber initWithDouble:]
# 0x7fffcae3b594 +[CALayer defaultValueForKey:]
# 0x7fffcaebd489 classDescription_locked()
# 0x7fffcaebc9fe classDescription_locked()
# 0x7fffcaebc9fe classDescription_locked()
# 0x7fffcaeb8292 classDescription()
# 0x7fffcaeb8495 CAObject_classInfo
# 0x7fffcae3bdf4 CA::Layer::class_state()
# 0x7fffcae3e081 -[CALayer init]
# 0x7fffc2d07854 -[NSView makeBackingLayer]
# 0x7fffc2d076db -[NSView(NSInternal) _createLayerAndInitialize]
# 0x7fffc2d06d4d -[NSView _doSetWantsLayerYES]
# 0x7fffc2d069da -[NSView setWantsLayer:]
# 0x7fffc2d142b6 __49-[NSThemeFrame _floatTitlebarAndToolbarFromInit:]_block_invoke
# 0x7fffc364b8b6 +[NSAnimationContext runAnimationGroup:]
# 0x7fffc2d13f23 -[NSThemeFrame _floatTitlebarAndToolbarFromInit:]
# 0x7fffc2d11a9c -[NSThemeFrame initWithFrame:styleMask:owner:]
# 0x7fffc2d10522 -[NSWindow _commonInitFrame:styleMask:backing:defer:]
# 0x7fffc2d0ec03 -[NSWindow _initContent:styleMask:backing:defer:contentView:]
# 0x7fffc2d0e65f -[NSWindow initWithContentRect:styleMask:backing:defer:]
# 0x1171ddebd -[QCocoaWindow initWithContentRect:styleMask:backing:defer:]
# 0x1171dddb1 -[NSWindow(QWidgetIntegration) qt_initWithQWidget:contentRect:styleMask:]
# 0x1171cee19 qt_mac_create_window()
# 0x1171ce119 QWidgetPrivate::createWindow_sys()
# 0x1171ce073 qt_mac_window_for()
# 0x1171d3b13 QWidgetPrivate::setModal_sys()
# 0x1172637c8 QWidget::create()
# 0x1175d5431 QToolBarPrivate::init()
# 0x1175d631c QToolBar::QToolBar()
# 0x111ca9c98 CvWindow::createToolBar()
Floating point exception: 8
and i've positioned that the cv2.imshow has the problem, but i don't know how?
if i just use the folloing code, it's ok
#!/usr/bin/env python
# coding=utf-8
import cv2
import numpy
import matplotlib.pyplot as plot
cap = cv2.VideoCapture(0)
while(1):
# get a frame
ret, frame = cap.read()
# show a frame
print frame.shape
cv2.imshow("capture", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
When you display an image in OpenCV you normally need to set a waitKey and release:
while(1):
test_data = []
ret, frame = cap.read()
frame = cv2.imread('hello.jpg')
h, w, _ = frame.shape
img = copy.deepcopy(frame)
img = pre_process(img)
test_data.append([img])
ret_res = _infer(inferer, test_data, threshold)
draw_result(frame, ret_res, h, w)
cv2.imshow("hellocapture", frame)
if cv2.waitKey(1) & 0xFF == ord('q')
break
cap.release()
cv2.destroyAllWindows()
am new here and also new to opencv.
I have this project at hand - designing an application that is able to interface with my computer webcam and take snapshot and also record videos.
So far so good this as far as I can go
import cv2 as cv
import numpy
cv.namedWindow ("camera", 1)
capture = cv.VideoCapture (0)
while True:
ret, frame = capture.read ()
img = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
cv.imshow ("camera", img)
if cv.waitKey(10) & 0XFF == ord ("q")
break
capture.release ()
cv.destroyAllWindows ()
Now I think am suppose to use cv.VideoCapture.grab ()
And cv.VideoCapture.retrieve ()
But honestly I don't know how am gonna use.
Please I need your HELP
There's a great example of how to do that here:
http://docs.opencv.org/3.0-beta/doc/py_tutorials/py_gui/py_video_display/py_video_display.html
The example below will take a snapshot every 30 seconds and save it to a file with a unique timestamp:
import cv2 as cv
import time
import datetime
cv.namedWindow("camera", 1)
capture = cv.VideoCapture(0)
while True:
ret, frame = capture.read ()
frame = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
file = "C:\Python34\CpV\%s.png" % datetime.datetime.now().strftime("%d-%m-%y--%H-%M-%S")
cv.imwrite (file, frame)
#cv.imshow("camera", frame)
time.sleep(30)
capture.release()
cv.destroyAllWindows ()
Use code below to record webcam capture to file :
import cv2
import cv
cap = cv2.VideoCapture(0)
ret,img=cap.read()
height , width , layers = img.shape
fps=20
video = cv2.VideoWriter("rec_out.avi", cv.CV_FOURCC(*'DIVX'), fps, (img.shape[1], img.shape[0]))
while True:
ret,img=cap.read()
height , width , layers = img.shape
video.write(img)
cv2.imshow('Video', img)
#video.write(img)
if(cv2.waitKey(10) & 0xFF == ord('b')):
break
Okay I got to edit my code and it worked
Check it out
import cv2 as cv
import time
cv.namedWindow("camera", 1)
capture = cv.VideoCapture(0)
while True:
ret, frame = capture.read ()
frame = cv.cvtColor (frame, cv.COLOR_BGR2BGRA)
file = "C:\Python34\CpV\test.png"
cv.imwrite (file, frame)
cv.imshow("camera", frame)
#it takes a snapshot when "q" is pressed and closes
the window
if cv.waitKey(10) & 0xFF == ord ('q'):
break
capture.release()
cv.destroyAllWindows ()
This is as far as I have gotten, I need to edit a little to make it short and concise.
I was using OpenCV 2.4.6 and was running the following code successfully from OpenCV Python Tutorial-
import numpy as np
import cv2
cap = cv2.VideoCapture('slow.flv')
ret,frame = cap.read()
r,h,c,w = 250,90,400,125 # simply hardcoded the values
track_window = (c,r,w,h)
roi = frame[r:r+h, c:c+w]
hsv_roi = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
while(1):
ret ,frame = cap.read()
if ret == True:
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# apply meanshift to get the new location
ret, track_window = cv2.meanShift(dst, track_window, term_crit)
# Draw it on image
x,y,w,h = track_window
img2 = cv2.rectangle(frame, (x,y), (x+w,y+h), 255,2)
cv2.imshow('img2',img2)
k = cv2.waitKey(60) & 0xff
if k == 27:
break
else:
cv2.imwrite(chr(k)+".jpg",img2)
else:
break
cv2.destroyAllWindows()
cap.release()
Later on I started to using OpenCV 3.0 and replace some Lib files in site packages directory and also replaced CV2.pyd file.Then when I tried to run the same code, i am getting the following error-
Traceback (most recent call last):
File "D:\Backup\OpenCV_Python_Prac_files\Prac5.1.1_ Video Analysis_MeanShift.py", line 14, in
roi = frame[r:r+h, c:c+w]
TypeError: 'NoneType' object has no attribute '_getitem_'
Can anyone tell me what is the reason behind causing this problem?
Thanks in Advance.
The error says that your frame is None. Check the return value of the first call to cap.read