how to save pygame camera as video output - python

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.

Related

is there any way of embedding html into pygame

So, I am trying to create a virtual assistant in pygame, but I could not find any way of adding my search results into the window, I was planning to web scrape all the html with beatifulsoup and put that html into pygame, but the problem is that I don't know any way of how one can embed html inside pygame, and to be clear, I am not talking about embedding pygame to html, but putting html inside a pygame window
There's no way to do this directly in pygame. But you can use an external tool like wkhtmltoimage to render your HTML to an image and use that in pygame.
Here's a simple example using imgkit (a python wrapper for wkhtmltoimage):
import pygame
import imgkit
from io import BytesIO
def main():
config = imgkit.config(wkhtmltoimage=r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe')
pygame.init()
screen = pygame.display.set_mode((600, 480))
html = "<style type = 'text/css'> body { font-family: 'Arial' } </style><body><h1>Html rendering</h1><div><ul><li><em>using pygame</em></li><li><strong>using imgkit</strong></li></ul></div></body>"
img = imgkit.from_string(html, False, config=config)
surface = pygame.image.load(BytesIO(img)).subsurface((0,0,280,123))
r = 0
center = screen.get_rect().center
clock = pygame.time.Clock()
while True:
for event in pygame.event.get():
if event.type == pygame.QUIT:
return
screen.fill('white')
tmp = pygame.transform.rotozoom(surface, r, 1)
tmp_r = tmp.get_rect(center=center)
screen.blit(tmp, tmp_r)
r += 1
pygame.display.flip()
clock.tick(60)
if __name__ == '__main__':
main()

motion-project library with USB Camera [duplicate]

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()

How to use webcam with Python and Pygame with Windows? vidcap.Error: Cannot set capture resolution

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'.

Display IO Stream from Raspberry Pi Camera as video in PyGame

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()

pygame.error: file not a windows.bmp file (have looked at other similar questions but unsuccessful so far)

I'm very new to pygame, and am using the book "Beginning Game developement with Python and Pygame". I have pretty much typed the example code and keep getting the same
"pygame error: file not a windows.bmp file"
and would like to be able to load jpg/png as in the example in the book. I'm pretty sure I'm in the right directory for mine to work and the images I wanted to use are the same format as in the example. I have also searched for solutions but none of the answers seemed to work for me.
The code from the book is as follows (I have python 2.7.4, Ubuntu 13.04 and (I think) pygame 1.2.15):
background_image_filename = 'sushiplate.jpg'
mouse_image_filename = 'fugu.png'
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background_image_filename).convert()
mouse_cursor = pygame.image.load(mouse_image_filename).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
my version of the code so far:
import os.path
background = os.path.join('Documents/Python/Pygame','Background.jpg')
cursor_image = os.path.join('Documents/Python/Pygame','mouse.png')
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
screen.blit(background, (0,0))
x, y = pygame.mouse.get_pos()
x-= mouse_cursor.get_width() / 2
y-= mouse_cursor.get_height() / 2
screen.blit(mouse_cursor, (x, y))
pygame.display.update()
Thanks for your help :)
I can almost guarantee that you're getting your paths wrong. In your code, you've put in relative paths, meaning that pygame is looking for your assets in subfolders of the working directory (the directory where you execute your code).
A demo of how I think you would have to have things laid out and where your code is looking is below - in this example you would have a command prompt open in /home/your_username/Documents/my_games (or ~/Documents/my_games) and you'd be running python your_game_script.py.
|---home
|---your_username
|---Documents
|---some_subfolder
|---my_games
|---your_game_script.py
|---Documents
|---Python
|---Pygame
|---Background.jpg
|---mouse.png
This would work, but I suspect you don't have your folders set up this way, and that's the reason it's not working. If you run an interactive python prompt in the same folder as your game script, try the following:
import os
os.path.isfile('Documents/Python/Pygame/Background.jpg')
os.path.isfile('Documents/Python/Pygame/mouse.png')
I suspect the result will be false for both - meaning the files couldn't be found at that subfolder location. I would recommend that you have the following structure for your game files:
|---my_game
|---your_game_script.py
|---images
|---Background.jpg
|---mouse.png
Then in your_game_script.py you can load the files in the following way:
background = 'images/Background.jpg' #relative path from current working dir
cursor_image = 'images/mouse.png' #relative path from current working dir
import pygame
from pygame.locals import *
from sys import exit
pygame.init()
screen = pygame.display.set_mode((640, 480), 0, 32)
pygame.display.set_caption("Hello, World!")
background = pygame.image.load(background).convert()
mouse_cursor = pygame.image.load(cursor_image).convert_alpha()

Categories