I am making a simple pi camera app using pygame. But for some reason the preview window is running terribly. Can someone help me fix this. It looks terrible like this. There must be a better way of achieving this. Code is shown below:
import os
import sys
from click import command
import pygame
from datetime import datetime
import picamera
from io import BytesIO
from subprocess import call
pygame.init()
width = 1280
height = 720
screen = pygame.display.set_mode((width,height), 0)
isRec = True
menu = 0
camera = picamera.PiCamera()
camera.resolution = (width, height)
def drawMainBtns():
camImg = pygame.image.load('res/cam.png')
vcamImg = pygame.image.load('res/vcam.png')
galImg = pygame.image.load('res/gal.png')
camImg = pygame.transform.scale(camImg, (138,105))
screen.blit(camImg, (40,40))
vcamImg = pygame.transform.scale(vcamImg, (138,105))
screen.blit(vcamImg, (215,40))
galImg = pygame.transform.scale(galImg, (138,105))
screen.blit(galImg, (width - 138 - 40,height - 105 - 40))
def gallery():
print('Opened gallery')
screen.fill((255,255,255))
while True:
if menu == 0:
stream = BytesIO()
camera.capture(stream, use_video_port=True, format='rgb')
stream.seek(0)
image1 = pygame.image.frombuffer(stream.read(), (width,height), 'RGB')
image1 = pygame.transform.scale(image1,(width,height))
screen.blit(image1,(0,0))
drawMainBtns()
pygame.display.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
elif event.type == pygame.MOUSEBUTTONDOWN:
print(pygame.mouse.get_pos())
x, y = pygame.mouse.get_pos()
if menu == 0:
if x > 40 and x < 180:
if y > 40 and y < 160:
now = datetime.now()
t_string = now.strftime("%d-%m-%Y_%H-%M-%S")
camera.capture('pics/' + t_string + '.jpg')
print("Cheese!")
if x > 215 and x < 360:
if y > 40 and y < 150:
if isRec:
isRec = False
print('Started recording')
camera.start_recording('tmp/0.h264')
else:
isRec = True
print('Stopped recording')
camera.stop_recording()
now = datetime.now()
t_string = now.strftime("%d-%m-%Y_%H-%M-%S")
command = 'MP4Box -add tmp/0.h264 vids/' + t_string + '.mp4'
call(command, shell=True)
os.remove('tmp/0.h264')
if x > 1095 and x < 1230:
if y > 576 and y < 680:
menu = 1
gallery()
Please help me with this. This is incredibly important to me. I'm running a pi4.
EDIT I have optimized it a bit more so now pygame is running fin at normal speeds. picamera is taking up all of the resources.