How to open camera with pygame in Windows? - python

I want to open the camera with Python using the pygame module on a Windows 7 machine, but it's not working. I have previously used "/dev/video0" which is the read device in Linux. The pygame documentation just shows how to open a camera device in Linux. I am using pygame version 1.9.1 and Python 2.7.
How can I open the camera on a Windows device? When I try my existing script, the error I get is:
File "E:/test_python/open_cam2.py", line 10, in <module>
cam = pygame.camera.Camera("/dev/video0", (640, 480))
File "C:\Python27\lib\site-packages\pygame_camera_vidcapture.py", line 47, in init
self.dev = vidcap.new_Dev(device, show_video_window)
TypeError: an integer is required

Try this,
import pygame.camera
import pygame.image
import sys
pygame.camera.init()
cameras = pygame.camera.list_cameras()
print "Using camera %s ..." % cameras[0]
webcam = pygame.camera.Camera(cameras[0])
webcam.start()
# grab first frame
img = webcam.get_image()
WIDTH = img.get_width()
HEIGHT = img.get_height()
screen = pygame.display.set_mode( ( WIDTH, HEIGHT ) )
pygame.display.set_caption("pyGame Camera View")
while True :
for e in pygame.event.get() :
if e.type == pygame.QUIT :
sys.exit()
# draw frame
screen.blit(img, (0,0))
pygame.display.flip()
# grab next frame
img = webcam.get_image()

The pygame.camera module natively supports cameras under Windows since version 2.0.2. See a minimal example using the pygame.camera module (tested with Windows):
import pygame
import pygame.camera
pygame.init()
pygame.camera.init()
camera_list = pygame.camera.list_cameras()
camera = pygame.camera.Camera(camera_list[0])
window = pygame.display.set_mode(camera.get_size())
clock = pygame.time.Clock()
camera.start()
run = True
while run:
clock.tick(100)
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
camera_frame = camera.get_image()
window.fill(0)
window.blit(camera_frame, (0, 0))
pygame.display.flip()
pygame.quit()
exit()

This should work...
import pygame
import pygame.camera
pygame.init()
gameDisplay = pygame.display.set_mode((1280,720), pygame.RESIZABLE)
pygame.camera.init()
cam = pygame.camera.Camera(0,(1280,720))
cam.start()
while True:
img = cam.get_image()
gameDisplay.blit(img,(0,0))
pygame.display.update()
for event in pygame.event.get() :
if event.type == pygame.QUIT :
cam.stop()
pygame.quit()
exit()
I'm using windows 10 , pygame version 1.9.6

Related

pygame.error: Library not initialized although having been initialized

My code looks something like this:
import pygame
pygame.init()
running = True
score = 0
score_text = score_font.render("Score: " + str(score), False, (0, 0, 0))
def construct_window():
main_window.blit(bg, (0,0))
main_window.blit(score_text, (260,0))
def reset_score():
score = 0
while running:
for event in pygame.event.get():
#making the game quitable
if event.type == pygame.QUIT:
running = False
if some_condition:
reset_score()
construct_window()
pygame.quit()
so it works like a charm but after i close the window i get the error: pygame.error: Library not initialized. And the score wont reset after the condition is fullfiled while the code is still running.
So my problem here was that I used images, wiches location i got like this:
import pygame
import pkg_resources
pygame.init()
img = pygame.image.load(pkg_resources.resource_filename("main", "my_image.png"))
I guess pygame doesn't like pkg_resources.
If any body else encounters this problem my solution to getting the filepath dynamically is:
import sys
import pygame
pygame.init()
current_dict = sys.path[0]
img = pygame.image.load(current_dict + "my_image.png")

MoviePy preview showing besides screen blit

I've got a problem.
I'm creating the Game Menu which i want to be:
background as video file (using MoviePy)
buttons on the video
The problem is video is showing, but the button1 not.
Please help...
from moviepy.editor import *
import pygame
from pygame import mixer
import os
import cv2
print(os.getcwd())
# Initialization the PyGame
pygame.init()
# Create the screen
WIN = pygame.display.set_mode((0, 0), pygame.FULLSCREEN)
# Menu Background
background = pygame.image.load('Assets/background.png')
button1 = pygame.image.load('Assets/button.png')
# Background SOUND
mixer.music.load('Assets/mainmenumusic.mp3')
mixer.music.set_volume(0.2)
mixer.music.play(-1)
# Game TITLE and ICON
pygame.display.set_caption("Game Launcher") # title of the game
icon = pygame.image.load('Assets/icon.png') # define the icon variable
pygame.display.set_icon(icon) # set the window icon to the icon variable
# FPS Lock
FPS = 60
clip = VideoFileClip('Assets/particles.mp4', audio=False)
# Game loop
clock = pygame.time.Clock()
running = True
while running:
clock.tick(FPS)
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
WIN.blit(button1, (960, 540))
clip.preview(fullscreen=True)
pygame.display.update()
The button is not showing because you blit it before the background video so the video covers it. You can just try with:
clip.preview(fullscreen=True)
WIN.blit(button1, (960, 540))

Show and flip image using python

I am trying to encode a String to a QR code. Then show the QR code image on a display using python.
Here is my code:
import pyqrcode
from PIL import Image
import os
import pygame
from time import sleep
qr = pyqrcode.create("This is a string one")
qr.png("QR.png", scale=16)
pygame.init()
WIDTH = 1280
HEIGHT = 1080
scr = pygame.display.set_mode((WIDTH,HEIGHT),0,32)
img = pygame.image.load("QR.png")
scr.blit(img,(0,0))
pygame.display.flip()
sleep(3)
Now I want to display and flip the image in a loop.
I want to do it in a loop as the string ("This is a string one") is not constant. It will be updated (such as, I get string from mysql). When the string updates, I want to display the new QR code image after 3 seconds then flip it, then continue.
But when I put the code in a loop, it crashes and the image does not flip or update.
import pyqrcode
from PIL import Image
import os
import pygame
from time import sleep
while(1):
qr = pyqrcode.create("Nguyen Tran Thanh Lam")
qr.png("QR.png", scale=16)
pygame.init()
WIDTH = 1280
HEIGHT = 1080
scr = pygame.display.set_mode((WIDTH,HEIGHT),0,32)
img = pygame.image.load("QR.png")
scr.blit(img,(0,0))
pygame.display.flip()
sleep(5)
Update:
After 5 second, pygame-windows not flip. I must use Ctrl-C to Interrupt.
Traceback (most recent call last):
File "qr.py", line 18, in <module>
sleep(5)
KeyboardInterrupt
Thank you in advance.
pygame.display.flip doesn't flip the image, it updates the display/screen. To actually flip an image you have to use pygame.transform.flip.
There are various other problems, for example you should do the initialization, call pygame.display.set_mode and load the image before the while loop starts. After loading an image, call the convert or convert_alpha method to improve the blit performance:
img = pygame.image.load("QR.png").convert()
You also need to call pygame.event.pump() or use an event loop for event in pg.event.get():, otherwise the program will freeze because the OS thinks that your program has stopped responding.
To implement a timer you can use pygame.time.get_ticks. time.sleep makes your program unresponsive and should usually not be used in a game.
Here's an example:
import pygame as pg
def main():
screen = pg.display.set_mode((640, 480))
clock = pg.time.Clock() # A clock to limit the frame rate.
image = pg.Surface((100, 100))
image.fill((50, 90, 150))
pg.draw.rect(image, (120, 250, 70), (20, 20, 20, 20))
previous_flip_time = pg.time.get_ticks()
done = False
while not done:
for event in pg.event.get():
# Close the window if the users clicks the close button.
if event.type == pg.QUIT:
done = True
current_time = pg.time.get_ticks()
if current_time - previous_flip_time > 1000: # 1000 milliseconds.
# Flip horizontally.
image = pg.transform.flip(image, True, False)
previous_flip_time = current_time
screen.fill((30, 30, 30))
screen.blit(image, (100, 200))
# Refresh the display/screen.
pg.display.flip()
clock.tick(30) # Limit frame rate to 30 fps.
if __name__ == '__main__':
pg.init()
main()
pg.quit()

pygame not displaying my image

i started learning pygame and i followed some tutorials to make simple hello world project and it works but when i do it my self trying to display my image on the window nothing happen!
this is my code
__author__ = 'mohammed'
import sys
import pygame
import color
# -----------setup------------------------
pygame.init() # start pygame
screensize = (800, 600) # variable that we will use to declare screen size
screen = pygame.display.set_mode(screensize) # set the screen size
pad = pygame.image.load('2.png')
x = 100
y = 100
# -----------setup------------------------
# -------------------main loop------------
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:
sys.exit()
screen.blit(pad, (x, y))
screen.fill(red)
pygame.display.update()
i am importing my file that contain colors and their rgb :
red = (255, 0, 0)
It looks like you're filling the screen after the image is drawn, covering the image. Try switching the order of the rows:
screen.blit(pad, (x, y))
and
screen.fill(red)

How to update the display of Pygame only when there is fresh incoming data from another Python script?

I have a Python script that receives data through Bluetooth at not so regular intervals. Specifically it receives the coordinates of an image through Bluetooth. Using those coordinates I want to update the display of an image in a separate Pygame script. I don't want the Pygame display to close and open again. The Pygame script should run continuously and it should update the display of the image only when it receives new data.
Here is my Bluetooth script:
import bluetooth
server_sock = bluetooth.BluetoothSocket(bluetooth.RFCOMM)
port = 1
server_sock.bind(("", port))
server_sock.listen(1)
client_sock, address = server_sock.accept()
print "Accepted connection from ", address
while True:
data = client_sock.recv(1024)
print "received [%s]" % data
Any guidelines on how to achieve this behaviour would be appreciated!
Thank you
import pygame
from pygame.locals import *
def main():
# Initialise screen
pygame.init()
screen = pygame.display.set_mode((150, 50))
pygame.display.set_caption('Basic Pygame program')
# Fill background
background = pygame.Surface(screen.get_size())
background = background.convert()
background.fill((250, 250, 250))
# Display some text
font = pygame.font.Font(None, 36)
text = font.render("Hello There", 1, (10, 10, 10))
textpos = text.get_rect()
textpos.centerx = background.get_rect().centerx
background.blit(text, textpos)
# Blit everything to the screen
screen.blit(background, (0, 0))
pygame.display.flip()
# Event loop
while 1:
for event in pygame.event.get():
if event.type == QUIT:
return
screen.blit(background, (0, 0))
data = client_sock.recv(1024)
#do something with the data
pygame.display.flip()
if __name__ == '__main__': main()
I just got that from the example. You should be able to do whatever you want inside the game loop.

Categories