I am trying to make my raspberry pi detect face(s) in video feed from pi camera, this is my code
import time
import cv2
import sys
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
# camera settings
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640,480))
time.sleep(1)
# video input
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
# capture frame from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = frame.array
# face detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#show the frames
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
rawCapture.truncate(0)
if key == ord("q"):
break
I tried to run it, but i got this error message
Traceback (most recent call last):
File"/home/pi/pythonpy/videofacedet/craft/videofacedet(selfmade).py", line 21, in <module>
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1702, in capture_continuous
if not encoder.wait(self.CAPTURE_TIMEOUT):
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 395, in wait
self.stop()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 419, in stop
self._close_output()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 349, in _close_output
mo.close_stream(output, opened)
File "/usr/lib/python2.7/dist-packages/picamera/mmalobj.py", line 371, in close_stream
stream.flush()
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 238, in flush
self.array = bytes_to_rgb(self.getvalue(), self.size or self.camera.resolution)
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 127, in bytes_to_rgb
'Incorrect buffer length for resolution %dx%d' % (width, height))
PiCameraValueError: Incorrect buffer length for resolution 640x480
where did it go wrong? I am new to python programming so I get confused about how can I fix it and where to start. Thank you in advance for your answers
Your code doesn't seem to be indented properly. I would suggest indenting these lines:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
for (x, y, w, h) in faces:
to be indented the same as the line image = frame.array
I think that was the cause of the error since you're supposed to clear the current frame when you're done with it to prepare for the next frame and I see you're trying to do that with rawCapture.truncate(0).
Indentation is really important in python since that's how lines of code are treated as blocks. I see it as how curly braces in some programming languages treat lines of code as blocks.
I think maybe the framerate you set is too high, I delete the line camera.framerate= 32,then the camera window showed in screen.
Related
I'm a Newbie in OpenGl. I try to draw points with Pyglet. But if I change the configs of the window, to enable MSAA, the points disappear. For other primitives this is not the case. I think this is a OpenGL problem and not caused by Pyglet.
My goal is to use MSAA (for getting smooth lines) or config2 in example code and also see the points.
Please see the example code and switch between the different configs.
import pyglet
from pyglet.gl import *
config1 = Config(sample_buffers=1, samples=4)
config2 = Config(sample_buffers=1, samples=4, double_buffer=True)
window = pyglet.window.Window() # everything there, but no smooth line
# window = pyglet.window.Window(config = config1) # draws nothing
# window = pyglet.window.Window(config = config2) # draws only smooth line, points missing
batch = pyglet.graphics.Batch()
line = batch.add(2, pyglet.gl.GL_LINES, None, ('v2f', (270, 165, 370, 315)))
point = batch.add(2, pyglet.gl.GL_POINTS, None, ('v2f', (300, 165, 400, 315)))
#window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
It's a problem with MSAA but I don't really understand why my Points disappear. Any fixes/explanations?
How can I rotate a line in pygame using math module and every second rotate line delete old line. I've just used other code but the problem was old line rotate and so I watched an sunshine effect.
To easily assist you with a specific answer for your problem, you really need to show your code. Please see how to ask.
I've prepared a generic example that randomises one end point of a line when a mouse button is clicked.
# pyg_line_demo
import pygame
import random
def get_random_position():
"""return a random (x,y) position in the screen"""
return (random.randint(0, screen_width - 1), #randint includes both endpoints.
random.randint(0, screen_height - 1))
def random_line(line):
""" Randomise an end point of the line"""
if random.randint(0,1):
return [line[0], get_random_position()]
else:
return [get_random_position(), line[-1]]
# initialisation
pygame.init()
screen_width, screen_height = 640, 480
surface = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Lines')
clock = pygame.time.Clock() #for limiting FPS
FPS = 30
# initial line
line = [(10, 10), (200, 200)]
finished = False
while not finished:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
if event.type == pygame.MOUSEBUTTONDOWN:
line = random_line(line)
#redraw background
surface.fill(pygame.Color("white"))
#draw line
pygame.draw.aalines(surface, pygame.Color("blue"), False, line)
# update display
pygame.display.update()
#limit framerate
clock.tick(FPS)
pygame.quit()
You should be able to insert your line rotation function in place of the random_line() function.
Let us know if you have any further questions.
Now here is the code:
import cv2
import sys
cascPath = "haarcascade_frontalface_default.xml"
cascPath2= "haarcascade_eye.xml"
faceCascade = cv2.CascadeClassifier(cascPath)
eyeCascade=cv2.CascadeClassifier(cascPath2)
image = cv2.imread('face-04.jpg')
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30)
)
print("Found {0} faces!".format(len(faces)))
for (x, y, w, h) in faces:
cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)
Face_gray=gray[y:y+h, x:x+w]
Face_color=image[y:y+h, x:x+w]
eyes=eyeCascade.detectMultiScale(Face_gray)
for(ex, ey, ew, eh) in eyes:
cv2.rectangle(Face_color, (ex,ey),(ex+ew,ey+eh),(0, 255, 0), 2)
cv2.imshow("Faces found", image)
cv2.waitKey(0)
I have taken care of the path for the images as well as the XML file
I have reinstalled the software
I cannot understand why I am getting this type error. I have tried running the same code on another pc and it worked properly.
I had the same problem!
When you want to download the XML files for object detection, download them using the "Raw" button located at the top right corner. Then use "Save as" and store the file in your project directory.
First I got this error because I just "save as " the link.
I can run the same program in Windows. I can see my camera using lsusb in Ubuntu 16.04, 64 bits. The camera is an OSVR infrared camera.
My program is
import numpy as np
import cv2
camera = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = camera.read()
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('camera', frame)
# k = cv2.waitKey(30)
# When everything done, release the capture
camera.release()
cv2.destroyAllWindows()
The results are:
cwu#ubuntu:~/project/osvrCamera$ python test.py
select timeout
select timeout
OpenCV Error: Assertion failed (!buf.empty() && buf.isContinuous()) in imdecode_, file /tmp/binarydeb/ros-kinetic-opencv3-3.1.0/modules/imgcodecs/src/loadsave.cpp, line 490
Traceback (most recent call last):
File "test.py", line 8, in <module>
ret, frame = camera.read()
cv2.error: /tmp/binarydeb/ros-kinetic-opencv3-3.1.0/modules/imgcodecs/src/loadsave.cpp:490: error: (-215) !buf.empty() && buf.isContinuous() in function imdecode_
Check if the frame isn't empty() first (maybe cam/frame isn't fully initialised when you try to convert/display it:
import numpy as np
import cv2
camera = cv2.VideoCapture(0)
while(True):
# Capture frame-by-frame
ret, frame = camera.read()
if not frame.empty():
cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
cv2.imshow('camera', frame)
# k = cv2.waitKey(30)
# When everything done, release the capture
camera.release()
cv2.destroyAllWindows()
I am stuck when I try to place an image on my GUI. Based on the program I am working on, I am restricted to working with Python v2.7.11. I have a basic GUI that I pulled from elsewhere (shown below, top code). However, when I try to place an image using a similar process, my GUI goes away altogether (no other features show). Edit: The error I am receiving is "image "pyimage28" doesn't exist, even though I'm defining my image as 'bug.gif'. The full error message is shown in the second code snippet; both the code and the image are located in on the Desktop.
Based on another question on this site, my attempt is shown below, starting with the variable "label".
Ultimately, I would like to do two things.
Place an image in the upper left corner of the GUI in place of where the frame item was
Give that image properties, such that I can store x,y coordinates when I click somewhere on the image, or the coordinates show in real time outside of the image.
.
from Tkinter import *
import ttk
root = Tk()
content = ttk.Frame(root)
#frame = ttk.Frame(content, borderwidth=5, relief="sunken", width=200, height=100)
label = ttk.Label(root)
image1 = PhotoImage(file='bug.gif')
label['image'] = image1
latlbl = ttk.Label(content, text="Latitude")
latval = ttk.Entry(content)
lonlbl = ttk.Label(content, text="Longitude")
lonval = ttk.Entry(content)
onevar = BooleanVar()
twovar = BooleanVar()
threevar = BooleanVar()
onevar.set(True)
twovar.set(False)
threevar.set(True)
one = ttk.Checkbutton(content, text="One", variable=onevar, onvalue=True)
two = ttk.Checkbutton(content, text="Two", variable=twovar, onvalue=True)
three = ttk.Checkbutton(content, text="Three", variable=threevar, onvalue=True)
ok = ttk.Button(content, text="Okay")
cancel = ttk.Button(content, text="Cancel")
content.grid(column=0, row=0)
#frame.grid(column=0, row=0, columnspan=3, rowspan=2)
label.grid(column=0, row=0, columnspan=3, rowspan=2)
latlbl.grid(column=3, row=0, columnspan=1)
latval.grid(column=4, row=0, columnspan=2)
lonlbl.grid(column=3, row=1, columnspan=1)
lonval.grid(column=4, row=1, columnspan=2)
one.grid(column=0, row=3)
two.grid(column=1, row=3)
three.grid(column=2, row=3)
ok.grid(column=3, row=3)
cancel.grid(column=4, row=3)
label.pack()
root.mainloop()
The full code error is:
runfile('C:/Users/ajpung/Desktop/untitled9.py', wdir='C:/Users/ajpung/Desktop')
Traceback (most recent call last):
File "<ipython-input-1-1596c9c787bc>", line 1, in <module>
runfile('C:/Users/ajpung/Desktop/untitled9.py', wdir='C:/Users/ajpung/Desktop')
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 699, in runfile
execfile(filename, namespace)
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 74, in execfile
exec(compile(scripttext, filename, 'exec'), glob, loc)
File "C:/Users/ajpung/Desktop/untitled9.py", line 25, in <module>
label['image'] = image1
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1333, in __setitem__
self.configure({key: value})
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1326, in configure
return self._configure('configure', cnf, kw)
File "C:\Users\ajpung\AppData\Local\Continuum\Anaconda2\lib\lib-tk\Tkinter.py", line 1317, in _configure
self.tk.call(_flatten((self._w, cmd)) + self._options(cnf))
TclError: image "pyimage1" doesn't exist
The code you posted does not give the error you say it does when running in a standard python interpreter.
That being said, there is one critical bug in your code that will prevent it from working. You are using both grid and pack in the root window. You need to remove this line:
label.pack()
I thought I'd tried this before, but the problem isn't with Spyder. Switching root = Tk() to root = Toplevel() fixed the original issue.