I tried to Pygame.camera embedded in wxPython.
after some searching, I found out It can do with SDL_WINDOWID. but I conldn't make it
The image is my Goal(what i want to make)
http://kalten.tistory.com/entry/wxPython
Can you help me? I need just simple example
I don't care even if Camera Viewer with Simplecv(not pygame.camera)
Thank you!!!^^ Have a nice day
self.parent = parent
self.hwnd = self.GetHandle()
os.environ['SDL_VIDEODRIVER'] = 'windib'
os.environ['SDL_WINDOWID'] = str(self.hwnd)
From Pygame Tutorials Camera Module Introduction:
Capturing a Live Stream The rest of this tutorial will be based around
capturing a live stream of images. For this, we will be using the
class below. As described, it will simply blit a constant stream of
camera frames to the screen, effectively showing live video. It is
basically what you would expect, looping get_image(), blitting to the
display surface, and flipping it. For performance reasons, we will be
supplying the camera with the same surface to use each time.
class Capture(object):
def __init__(self):
self.size = (640,480)
# create a display surface. standard pygame stuff
self.display = pygame.display.set_mode(self.size, 0)
# this is the same as what we saw before
self.clist = pygame.camera.list_cameras()
if not self.clist:
raise ValueError("Sorry, no cameras detected.")
self.cam = pygame.camera.Camera(self.clist[0], self.size)
self.cam.start()
# create a surface to capture to. for performance purposes
# bit depth is the same as that of the display surface.
self.snapshot = pygame.surface.Surface(self.size, 0, self.display)
def get_and_flip(self):
# if you don't want to tie the framerate to the camera, you can check
# if the camera has an image ready. note that while this works
# on most cameras, some will never return true.
if self.cam.query_image():
self.snapshot = self.cam.get_image(self.snapshot)
# blit it to the display surface. simple!
self.display.blit(self.snapshot, (0,0))
pygame.display.flip()
def main(self):
going = True
while going:
events = pygame.event.get()
for e in events:
if e.type == QUIT or (e.type == KEYDOWN and e.key == K_ESCAPE):
# close the camera safely
self.cam.stop()
going = False
self.get_and_flip()
Since get_image() is a blocking call that could take quite a bit of
time on a slow camera, this example uses query_image() to see if the
camera is ready. This allows you to separate the framerate of your
game from that of your camera. It is also possible to have the camera
capturing images in a separate thread, for approximately the same
performance gain, if you find that your camera does not support the
query_image() function correctly.
Related
I am very new to python and I am working on a project using pygame and cv2
My first python file code has an output image that shows up in a pygame window, but I have another python file that detects objects and it gets an input video like this:
cap = cv2.VideoCapture("video.mp4")
and then it reads the video and shows the detected objects in the video by surrounding boxes around each object.
I want the cap = cv2.VideoCapture() to get the live video from the pygame window and maybe show the boxes of object detection in a second window or the same pygame window (not sure right now what I want, but maybe showing it in the same pygame window would be better)
I am not sure if this is enough information to help me since I am not very familiar with pygame or cv2, please let me know.
In pygame you are actually drawing on a Surface object. You can get the pygame.Surface object associated with the display with pygame.display.get_surface():
screen = pygame.display.get_surface()
Use pygame.surfarray.pixels3d to create a new 3D array that directly references the pixel values in the Surface. This is equivalent to a cv2 matrix respectively NumPy array when you transpose the x and y axis and transform from RGB to BGR:
capture = pygame.surfarray.pixels3d(screen)
capture = capture.transpose([1, 0, 2])
capture_bgr = cv2.cvtColor(capture, cv2.COLOR_RGB2BGR)
Do this once per frame after updating the display:
def capture_frame():
screen = pygame.display.get_surface()
capture = pygame.surfarray.pixels3d(screen)
capture = capture.transpose([1, 0, 2])
capture_bgr = cv2.cvtColor(capture, cv2.COLOR_RGB2BGR)
return capture_bgr
run = True
while run:
for event in pygame.event.get():
if event.type == pygame.QUIT:
run = False
# draw
# [...]
pygame.display.flip()
frame_img = capture_frame()
# [...]
I'm making a simulation for school and I'm trying to make pygame create a fullscreen display in my native resolution. However, I have a QHD screen (2560x1440), and it isn't working properly. As far as I can tell, pygame is rendering a screen at the correct resolution, but expanding it so it is scaled as if it were 1080p, so about 300-400 pixels are cut off around the edges. This causes, for example, a circle rendered at (200,200) to be completely invisible. After some research, I learned that this is because pygame doesn't officially support my resolution (it is not listed in pygame.display.list_modes()). Is there any way to force it to work? I would prefer if I could use my actual resolution instead of upscaled 1080p.
Here is the code that initializes the window:
import pygame
from pygame.locals import *
pygame.init()
w = pygame.display.Info().current_w
h = pygame.display.Info().current_h
S = pygame.display.set_mode((w,h), pygame.FULLSCREEN)
If you are using Windows, make sure in your display settings you have scaling set to 100%. This will make your text and everything smaller if you don't have it at that currently but I think Pygame windows get affected by this number for some reason.
See the below code snippet for making sure your window scales properly. Also see here.
import pygame
from ctypes import windll
def run():
# Force windows to ignore the display scaling value.
windll.user32.SetProcessDPIAware()
pygame.display.init()
# Make the screen the highest resolution that will fit the screen at 100% scaling.
screen = pygame.display.set_mode(pygame.display.list_modes()[0])
done = False
while not done:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN:
if event.key == pygame.K_ESCAPE:
done = True
pygame.display.flip()
pygame.quit()
if __name__ == "__main__":
run()
I've written a small script to display album art on USB display (on Raspberry Pi) by writing to the framebuffer with pygame. The script is working perfectly and the album art is displayed on the screen for 3 seconds:
def set_image(image):
""" Set the USB display image using pygame (320px x 240px) """
pygame.display.init()
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
black = 0, 0, 0
screen = pygame.display.set_mode(size)
pygame.mouse.set_visible(False)
pygame_image = pygame.image.fromstring(image.tobytes(), image.size, image.mode)
pygame_image_rect = pygame_image.get_rect()
screen.fill(black)
screen.blit(pygame_image, (40, 0))
pygame.font.init()
pygame.display.update()
time.sleep(3)
The problem is that when the script finishes, pygame (correctly) clears the framebuffer and my image disappears. Is there any way to tell it to leave the contents of the framebuffer when quitting?
Are you calling pygame.quit?
Generally:
- don't run window server (run from console)
- use flip to flip to a different surface
- don't call pygame.quit when exiting.
It is hard to guarantee what happens after that, but flip should flip the screen buffer to a different part of memory than the shell uses, so it won't get overwritten, and if you don't call pygame.quit, it should leave it in the (bad) state. Although there are scenarios this is useful.
For some (but not all!) images, copying a surface using surface.copy() loses the transparency. So I've got two questions?
Why does copy lose the transparency? The docs sound like everything about the new surface should be the same, but that's obviously not happening.
Why does this happen with some images and not others?
Here is an example "bad" image -- when copied, the transparency is lost
Here is an example "good" image -- when copied, the transparency is not lost.
And here is the code that you can run to see the difference:
import pygame
def test():
screen = pygame.display.set_mode((320, 240))
bad_original = pygame.image.load('bad-image.gif')
bad_copied = bad_original.copy()
good_original = pygame.image.load('good-image.gif')
good_copied = good_original.copy()
while True:
for event in pygame.event.get():
if (event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE or
event.type == pygame.QUIT):
pygame.quit()
screen.fill((150, 150, 150))
screen.blit(bad_original, (0,0))
screen.blit(bad_copied, (100, 0))
screen.blit(good_original, (0,100))
screen.blit(good_copied, (100, 100))
pygame.display.flip()
if __name__ == '__main__':
test()
And heck, for completion, here's what a screenshot of running the above code looks like.
Please note that I'm not looking for workarounds; I just want to know what I am not understanding about surface.copy, or anything you think I may not understand about working with Pygame surfaces.
I'm using Python 3.3 and Pygame 1.9.2pre on a Windows 7 machine.
You need to use .convert_alpha()
Try:
pygame.image.load('my_image.gif').convert_alpha()
See:
http://www.pygame.org/docs/ref/surface.html#pygame.Surface.convert_alpha
"Creates a new copy of the surface with the desired pixel format. The new surface will be in a format suited for quick blitting to the given format with per pixel alpha. If no surface is given, the new surface will be optimized for blitting to the current display.
Unlike the Surface.convert() method, the pixel format for the new image will not be exactly the same as the requested source, but it will be optimized for fast alpha blitting to the destination."
In pygame anytime you load and image, or create a surface, with the intent of displaying it you should .convert() it if it has no transparency, or .convert_alpha() it if it has transparency. This yields both a big speedup AND solves the mystery of, 'Why is my transparency doing that?'.
I've just started learning how to use pygame yesterday. I was read this one book that was super helpful and followed all its tutorials and examples and stuff. I wanted to try making a really simple side scroller/platforming game but the book sorta jumped pretty fast into 3D modeling with out instructing how to make changing sprites for movement of up down left and right and how to cycle through animating images.
I've spent all today trying to get a sprite to display and be able to move around with up down left and right. But because of the simple script it uses a static image and refuses to change.
Can anyone give me some knowledge on how to change the sprites. Or send me to a tutorial that does?
Every reference and person experimenting with it ha always been using generated shapes so I'm never able to work with them.
Any help is very appreciated.
Added: before figuring out how to place complex animations in my scene I'd like to know how I can make my 'player' change to unmoving images in regards to my pressing up down left or right. maybe diagonal if people know its something really complicated.
Add: This is what I've put together so far. http://animania1.ca/ShowFriends/dev/dirmove.rar would there be a possibility of making the direction/action set the column of the action and have the little column setting code also make it cycle down in a loop to do the animation? (or would that be a gross miss use of efficiency?)
Here is a dumb example which alernates between two first images of the spritesheet when you press left/right:
import pygame
quit = False
pygame.init()
display = pygame.display.set_mode((640,480))
sprite_sheet = pygame.image.load('sprite.bmp').convert()
# by default, display the first sprite
image_number = 0
while quit == False:
event = pygame.event.poll()
no_more_events = True if event == pygame.NOEVENT else False
# handle events (update game state)
while no_more_events == False:
if event.type == pygame.QUIT:
quit = True
break
elif event.type == pygame.NOEVENT:
no_more_events = True
elif event.type == pygame.KEYDOWN:
if event.key == pygame.K_LEFT:
image_number = 0
elif event.key == pygame.K_RIGHT:
image_number = 1
event = pygame.event.poll()
if quit == False:
# redraw the screen
display.fill(pygame.Color('white'))
area = pygame.Rect(image_number * 100, 0, 100, 150)
display.blit(sprite_sheet, (0,0), area)
pygame.display.flip()
I've never really used Pygame before so maybe this code shoudln't really be taken as an example. I hope it shows the basics though.
To be more complete I should wait some time before updating, e.g. control that I update only 60 times per second.
It would also be handy to write a sprite class which would simplify your work. You would pass the size of a sprite frame in the constructor, and you'd have methodes like update() and draw() which would automatically do the work of selecting the next frame, blitting the sprite and so on.
Pygame seems to provide a base class for that purpose: link text.
dude the only thing you have to do is offcourse
import pygame and all the other stuff needed
type code and stuff..........then
when it comes to you making a spri
class .your class nam here. (pygame.sprite.Sprite):
def __init__(self):
pygame.sprite.Sprite.init(self)
self.image=pygame.image.load(your image and path)
self.rect=self.image.get_rect()
x=0
y=0
# any thing else is what you want like posistion and other variables
def update(self):
self.rect.move_ip((x,y))
and thats it!!!! but thats not the end. if you do this you will ony have made the sprite
to move it you need
I don't know much about Pygame, but I've used SDL (on which Pygame is based).
If you use Surface.blit(): link text
You can use the optional area argument to select which part of the surface to draw.
So if you put all the images that are part of the animation inside a single file, you can select which image will be drawn.
It's called "clipping".
I guess you will have a game loop that will update the game state (changing the current image of the sprite if necessary), then draw the sprites using their state.