I am trying to initialize the camera module in pygame and display video from a usb webcam. This is my code:
import pygame
import pygame.camera
from pygame.camera import *
from pygame.locals import *
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(640,480))
cam.start()
image = cam.get_image()
Yet i get this error:
Traceback (most recent call last):
File "C:/Users/Freddie/Desktop/CAMERA/Test1.py", line 7, in <module>
pygame.camera.init()
File "C:\Python27\lib\site-packages\pygame\camera.py", line 67, in init
_camera_vidcapture.init()
File "C:\Python27\lib\site-packages\pygame\_camera_vidcapture.py", line 21, in init
import vidcap as vc
ImportError: No module named vidcap
PLS HELP!!! Im on Windows
I met the same problem.
The error info of "ImportError: No module named vidcap" indicates that python interpreter didn't find the vidcap module on you machine.
so you'd better follow these steps.
Download the vidcap from http://videocapture.sourceforge.net/
2.Then copy the corresponding version of dll (which named "vidcap.pyd" in VideoCapture-0.9-5\VideoCapture-0.9-5\Python27\DLLs) to "your python path"\DLLs\ .
3.restart you script.
Done!.
The camera module can only be used on linux
I met the same problem but I found out that its not included on windows ONLY LINUX
Try this:
import pygame
import pygame.camera
import time, string
from VideoCapture import Device
from pygame.locals import *
pygame.camera.init()
cam = pygame.camera.Camera(0,(640,480),"RGB")
cam.start()
img = pygame.Surface((640,480))
cam.get_image(img)
pygame.image.save(img, "img2.jpg")
cam.stop()
The pygame.camera is only supported on linux:
Pygame currently supports only Linux and v4l2 cameras.
An alternative solution is to use the OpenCV VideoCapture. Install OpenCV for Python (cv2) (see opencv-python).
Opens a camera for video capturing:
capture = cv2.VideoCapture(0)
Grabs a camera frame:
success, camera_image = capture.read()
Convert the camera frame to a pygame.Surface object using pygame.image.frombuffer:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
See also Camera and Video
Minimal example:
import pygame
import cv2
capture = cv2.VideoCapture(0)
success, camera_image = capture.read()
window = pygame.display.set_mode(camera_image.shape[1::-1])
clock = pygame.time.Clock()
run = success
while run:
clock.tick(60)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
success, camera_image = capture.read()
if success:
camera_surf = pygame.image.frombuffer(
camera_image.tobytes(), camera_image.shape[1::-1], "BGR")
else:
run = False
window.blit(camera_surf, (0, 0))
pygame.display.flip()
pygame.quit()
exit()
Related
I'm using multiprocessing to display screenshot with the mss module from pygame. However, the hello message is displayed three times.
I'm wondering if this will distract performance. Also when I close the screen of pygame the console keeps on running. Here is my code:
from mss import mss
from multiprocessing import Process, Queue
import pygame
import pygame.display
import pygame.image
import pygame.time
import pygame.font
import pygame.event
from pygame.locals import *
from numpy import asarray
from cv2 import resize, cvtColor, COLOR_BGRA2BGR
SCR_SIZE = (640, 480)
def grabber(queue: Queue):
global SCR_SIZE
with mss() as sct:
while True:
queue.put(cvtColor(resize(asarray(sct.grab(sct.monitors[1])), SCR_SIZE), COLOR_BGRA2BGR).tobytes())
def displayer(queue: Queue):
global SCR_SIZE
pygame.init()
SCR = pygame.display.set_mode(SCR_SIZE, DOUBLEBUF)
SCR.set_alpha(None)
clock = pygame.time.Clock()
FONT_COMIC = pygame.font.SysFont('Cambria Math', 20)
isGameRunning = True
while isGameRunning:
for EVENT in pygame.event.get():
if EVENT.type == pygame.QUIT:
isGameRunning = False
clock.tick(60)
currentFrame = queue.get()
if currentFrame is not None:
SCR.blit(pygame.image.frombuffer(currentFrame, SCR_SIZE, 'BGR'), (0,0))
else:
break
SCR.blit(FONT_COMIC.render('FPS:'+str(clock.get_fps())[:5], False, (0,255,0)),(10,10))
pygame.display.update()
if __name__ == "__main__":
queue = Queue()
Process(target=grabber, args=(queue,)).start()
Process(target=displayer, args=(queue,)).start()
So if you run this it will run perfectly, but will display the community message three times:
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
pygame 2.0.1 (SDL 2.0.14, Python 3.9.5)
Hello from the pygame community. https://www.pygame.org/contribute.html
When you run Process with a method from the same file, you basically have the same imports: once for the main script, and twice more for each Process instance.
You can move the import ... statements under the specific method. For example:
def displayer(queue: Queue):
import pygame
...
So I downloaded the windows wheel for Video Capture in my Pygame. But when I create a webcam instance I'm getting the error below. The code worked well until I started to implement the camera module. I've seen very few answers and they were from 2013. I was hoping Pygame would've improved on Windows more since then, but it's most likely me that's causing the problem. Any suggestions?
import pygame
import pygame.camera
pygame.init()
# https://www.lfd.uci.edu/~gohlke/pythonlibs/#videocapture need to get the VideoCapture whl
pygame.camera.init()
webcam = pygame.camera.Camera(0, (640, 480), "RGB")
webcam.start()
pygame.display.set_caption("S.H.A.N.E.")
icon = pygame.image.load("SHANE pic.jpg")
pygame.display.set_icon(icon)
background = pygame.image.load("SHANE pic.jpg")
# (WIDTH, HEIGHT)
screen_width = 800
screen_height = 600
screen = pygame.display.set_mode((screen_width, screen_height))
running = True
while running:
# STARTING POINT (L/R, T/B), ENDING POINT (L/R, T/B)
screen.fill((0, 0, 0))
img = webcam.get_image()
screen.blit(img, (0, 0))
pygame.display.flip()
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
Here's the error I'm getting.
Traceback (most recent call last):
File "C:/Users/Notebook/PycharmProjects/Jarvis/Gui2.py", line 10, in <module>
webcam = pygame.camera.Camera(0, (640, 480), "RGB")
File "C:\Users\Notebook\AppData\Local\Programs\Python\Python37-32\lib\site-<packages\pygame\_camera_vidcapture.py", line 60, in __init__
self.dev.setresolution(width, height)
vidcap.Error: Cannot set capture resolution.
webcam = pygame.camera.Camera("/dev/video0",(640,480))
You do not place the coordinates/size/scale of the camera where you have placed them, that is reserved for the file input.
Cheers!
Docs:
https://www.pygame.org/docs/tut/CameraIntro.html
You can use the following code to check what camera(s) you have.
pygame.camera.init()
camlist = pygame.camera.list_cameras()
print(camlist)
For example, mine prints ['FaceTime HD Camera']. Then you go
cam = pygame.camera.Camera('FaceTime HD Camera', (640,480))
If you mean yours prints ['0'], I wonder if you can fix the problem by simply changing 0 to '0'.
I reinstall pygame 3 times but issue not get resolved. Below is my code.
import pygame
import pygame.camera
import time
pygame.init()
pygame.camera.init()
camlist = pygame.camera.list_cameras()
cam = pygame.camera.Camera("C:/Program Files/iBall Face2Face ROBO K20 Webcam/VideoCap",(640,480))
cam.start()
time.sleep(0.1) # You might need something higher in the beginning
img = cam.get_image()
pygame.image.save(img,"C:/Users/mswatg05/Desktop/filename.jpg")
cam.stop()
By default, the camera extension is only enabled on linux builds. Try using a third party compile, and install VideoCapture from the same place.
I was try this tutorial Stream Webcam Video to PyGame nothing error.. https://www.youtube.com/watch?v=H6ijuSmv5N0
and the script like this..
import pygame, sys
import pygame.camera
from pygame.locals import *
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640, 480))
cam = pygame.camera.Camera("/dev/video0", (640, 480))
cam.start()
while 1:
image = cam.get_image()
screen.blit(image, (0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
#save as video output
sys.exit()
But.. in here I have a problem when I want to save that Stream as video output.. like a mp4, 3gp, avi and other.
In this thread pygame.image.save(img, "image.jpg") save the output as image.
https://stackoverflow.com/a/20502651/3445802
Pygame's multimedia output capabilities are severily limited:
It can only save uncompressed BMP images, and there is no way it can save a video format.
You have to make use of another library which to feed image frames, to render the video - or save frame by frame in a folder, numbering the file names in crescent order, and convert the result to a video with an utility later.
This project seens to feature a class to call libffmpeg to encode videos, passing frame by frame in a Python call:
https://github.com/kanryu/pipeffmpeg - you will just need a way to convert the pygame Surface object to the expected "frameraw" attribute of
ffmpeg.
https://github.com/kanryu/pipeffmpeg/blob/master/pipeffmpeg.py
You can use pygame to capture frames. If you store those to disk, you can then use any software you like to convert those frames to any video format you like.
Modifying your example marginally, this can be done as follows:
import pygame, sys, os
import pygame.camera
from pygame.locals import *
pygame.init()
pygame.camera.init()
# Ensure we have somewhere for the frames
try:
os.makedirs("Snaps")
except OSError:
pass
screen = pygame.display.set_mode((640, 480))
cam = pygame.camera.Camera("/dev/video0", (640, 480))
cam.start()
file_num = 0
done_capturing = False
while not done_capturing:
file_num = file_num + 1
image = cam.get_image()
screen.blit(image, (0,0))
pygame.display.update()
# Save every frame
filename = "Snaps/%04d.png" % file_num
pygame.image.save(image, filename)
for event in pygame.event.get():
if event.type == pygame.QUIT:
done_capturing = True
# Combine frames to make video
os.system("avconv -r 8 -f image2 -i Snaps/%04d.png -y -qscale 0 -s 640x480 -aspect 4:3 result.avi")
I've used this to create stop motion software which can be used with scouts/cubs. The code is also deliberately simple, so a couple of links to these which may be helpful.
Couple of links:
http://www.sparkslabs.com/camination/
https://github.com/sparkslabs/camination
i´m not at home now but my workarround is take the pygame surface and convert to numpy array and write with opencv to mp4 movie.
I'm working on a project that requires me to have a viewfinder (barcode scanner).
I'm doing this with the Raspberry Pi Camera Module by the picamera python module, and I've got the whole detection and whatnot programmed.
Now I need to figure out how to display the preview from the Pi's Camera Module in a PyGame movie module.
(If there's a better way to display video from an IO Stream in PyGame, please let me know.)
The reason I need to display it in PyGame is because I'll need to overlay controls on top of the video and be able to get input from a touchscreen I'm going to use as the viewfinder/screen for the Pi/project.
As far as I can see from the pygame.movie documentation, pygame.movie only loads from a file. Is there a way that I could convert the stream into a file-like object and have PyGame play from that?
Basically put, I need a way to take the io.BytesIO stream created in this example code, and display it in PyGame.
If I understand excatly , you need to instant and infinite preview from camera module to your screen.
there is a way that I figure it out. first you must install Official V4L2 driver.
sudo modprobe bcm2835-v4l2
reference https://www.raspberrypi.org/forums/viewtopic.php?f=43&t=62364
and than you should create a python file to compile and code this
import sys
import pygame
import pygame.camera
pygame.init()
pygame.camera.init()
screen = pygame.display.set_mode((640,480),0)
cam_list = pygame.camera.list_cameras()
cam = pygame.camera.Camera(cam_list[0],(32,24))
cam.start()
while True:
image1 = cam.get_image()
image1 = pygame.transform.scale(image1,(640,480))
screen.blit(image1,(0,0))
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
cam.stop()
pygame.quit()
sys.exit()
this code from http://blog.danielkerris.com/?p=225 , in this blog they did with a webcam. you define your camera module as a webcam with v4l2 driver
also you should check this tutorial https://www.pygame.org/docs/tut/camera/CameraIntro.html
I hope this will works for you
You can do this with the 'pygame.image.frombuffer' command.
Here's an example:
import picamera
import pygame
import io
# Init pygame
pygame.init()
screen = pygame.display.set_mode((0,0))
# Init camera
camera = picamera.PiCamera()
camera.resolution = (1280, 720)
camera.crop = (0.0, 0.0, 1.0, 1.0)
x = (screen.get_width() - camera.resolution[0]) / 2
y = (screen.get_height() - camera.resolution[1]) / 2
# Init buffer
rgb = bytearray(camera.resolution[0] * camera.resolution[1] * 3)
# Main loop
exitFlag = True
while(exitFlag):
for event in pygame.event.get():
if(event.type is pygame.MOUSEBUTTONDOWN or
event.type is pygame.QUIT):
exitFlag = False
stream = io.BytesIO()
camera.capture(stream, use_video_port=True, format='rgb')
stream.seek(0)
stream.readinto(rgb)
stream.close()
img = pygame.image.frombuffer(rgb[0:
(camera.resolution[0] * camera.resolution[1] * 3)],
camera.resolution, 'RGB')
screen.fill(0)
if img:
screen.blit(img, (x,y))
pygame.display.update()
camera.close()
pygame.display.quit()