Pygame rotate line delete old line - python-2.7

How can I rotate a line in pygame using math module and every second rotate line delete old line. I've just used other code but the problem was old line rotate and so I watched an sunshine effect.

To easily assist you with a specific answer for your problem, you really need to show your code. Please see how to ask.
I've prepared a generic example that randomises one end point of a line when a mouse button is clicked.
# pyg_line_demo
import pygame
import random
def get_random_position():
"""return a random (x,y) position in the screen"""
return (random.randint(0, screen_width - 1), #randint includes both endpoints.
random.randint(0, screen_height - 1))
def random_line(line):
""" Randomise an end point of the line"""
if random.randint(0,1):
return [line[0], get_random_position()]
else:
return [get_random_position(), line[-1]]
# initialisation
pygame.init()
screen_width, screen_height = 640, 480
surface = pygame.display.set_mode((screen_width,screen_height))
pygame.display.set_caption('Lines')
clock = pygame.time.Clock() #for limiting FPS
FPS = 30
# initial line
line = [(10, 10), (200, 200)]
finished = False
while not finished:
for event in pygame.event.get():
if event.type == pygame.QUIT:
finished = True
if event.type == pygame.MOUSEBUTTONDOWN:
line = random_line(line)
#redraw background
surface.fill(pygame.Color("white"))
#draw line
pygame.draw.aalines(surface, pygame.Color("blue"), False, line)
# update display
pygame.display.update()
#limit framerate
clock.tick(FPS)
pygame.quit()
You should be able to insert your line rotation function in place of the random_line() function.
Let us know if you have any further questions.

Related

How to use GL_POINTS and MSAA in OpenGL

I'm a Newbie in OpenGl. I try to draw points with Pyglet. But if I change the configs of the window, to enable MSAA, the points disappear. For other primitives this is not the case. I think this is a OpenGL problem and not caused by Pyglet.
My goal is to use MSAA (for getting smooth lines) or config2 in example code and also see the points.
Please see the example code and switch between the different configs.
import pyglet
from pyglet.gl import *
config1 = Config(sample_buffers=1, samples=4)
config2 = Config(sample_buffers=1, samples=4, double_buffer=True)
window = pyglet.window.Window() # everything there, but no smooth line
# window = pyglet.window.Window(config = config1) # draws nothing
# window = pyglet.window.Window(config = config2) # draws only smooth line, points missing
batch = pyglet.graphics.Batch()
line = batch.add(2, pyglet.gl.GL_LINES, None, ('v2f', (270, 165, 370, 315)))
point = batch.add(2, pyglet.gl.GL_POINTS, None, ('v2f', (300, 165, 400, 315)))
#window.event
def on_draw():
window.clear()
batch.draw()
pyglet.app.run()
It's a problem with MSAA but I don't really understand why my Points disappear. Any fixes/explanations?

Module that loops through two image and is toggled by keyboard commands

I'm trying to construct a module that loops through two or more images when a key is pressed and stops looping when the key is lifted. Unfortunately, once I get the images to start looping, they don't stop. Please help, I'm programming this in Python 2.7 and with Pygame. Here is my commented code.
import pygame, sys
running = True
run = False
pygame.init()
screen = pygame.display.set_mode([640,480]) #Initializes pygame window
screen.fill([255, 255, 255]) #Fills screen with white
picture = pygame.image.load('picture1.png') #Loads image 1
picturetwo = pygame.image.load('picture2.png') #Loads image 2
screen.blit(picture, [50, 50])
import pygame, sys
running = True
run = False
pygame.init()
screen = pygame.display.set_mode([640,480]) #Initializes pygame window
screen.fill([255, 255, 255]) #Fills screen with white
picture = pygame.image.load('picture1.png') #Loads image 1
picturetwo = pygame.image.load('picture2.png') #Loads image 2
screen.blit(picture, [50, 50])
#Places picture in window. 50 pixels down from the top and 50 pixels right from the top
pygame.display.flip()
while running:
for event in pygame.event.get():
if event.type == pygame.KEYDOWN and event.key == pygame.K_RIGHT:
#If a key is pressed #If that key is the right arrow
run = True
while run == True:
pygame.time.delay(500)
pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
#Creates a white rectangle to fill over the preceding image
screen.blit(picturetwo, [50, 50])
#Loads the second image over the first rectangle
pygame.display.flip()
#Repeats
pygame.time.delay(500)
pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
screen.blit(picture, [50, 50])
pygame.display.flip()
if event.key != pygame.K_RIGHT:
#If the right key is not pressed, exits loop. DOES NOT WORK
run = False
if event.type == pygame.QUIT: #Exits program
running = False
pygame.quit()
You are using the event KEYDOWN to check if a key is kept pressed. It does not work that way. The event is emitted the moment you press the key only. See this post for a more detailed explanation.
To check if a key is pressed, use:
pressed = pygame.key.get_pressed()
if pressed[pygame.K_RIGHT]: #or the constant corresponding to the key to check
#do things to do when that key is pressed.
You could try to rewrite your while loop this way:
while running:
#check the incoming events, just to check when to quit
for event in pygame.event.get():
if event.type == pygame.QUIT: #Exits program
running = False
pressed = pygame.key.get_pressed()
if pressed[K_RIGHT]:
pygame.time.delay(500)
pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
#Creates a white rectangle to fill over the preceding image
screen.blit(picturetwo, [50, 50])
#Loads the second image over the first rectangle
pygame.display.flip()
#Repeats
pygame.time.delay(500)
pygame.draw.rect(screen, [255,255,255], [50, 50, 150, 150], 0)
screen.blit(picture, [50, 50])
pygame.display.flip()

piCameraValueError : Incorrect buffer length for resolution 640x480

I am trying to make my raspberry pi detect face(s) in video feed from pi camera, this is my code
import time
import cv2
import sys
import numpy as np
from picamera.array import PiRGBArray
from picamera import PiCamera
# camera settings
camera = PiCamera()
camera.resolution = (640, 480)
camera.framerate = 32
rawCapture = PiRGBArray(camera, size=(640,480))
time.sleep(1)
# video input
faceCascade = cv2.CascadeClassifier('/home/pi/opencv-3.1.0/data/haarcascades/haarcascade_frontalface_default.xml')
# capture frame from the camera
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
image = frame.array
# face detection
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
gray,
scaleFactor=1.1,
minNeighbors=5,
minSize=(30, 30),
flags=cv2.CASCADE_SCALE_IMAGE
)
# Draw a rectangle around the faces
for (x, y, w, h) in faces:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
#show the frames
cv2.imshow("Frame", image)
key = cv2.waitKey(1) & 0xFF
rawCapture.truncate(0)
if key == ord("q"):
break
I tried to run it, but i got this error message
Traceback (most recent call last):
File"/home/pi/pythonpy/videofacedet/craft/videofacedet(selfmade).py", line 21, in <module>
for frame in camera.capture_continuous(rawCapture, format="bgr", use_video_port=True):
File "/usr/lib/python2.7/dist-packages/picamera/camera.py", line 1702, in capture_continuous
if not encoder.wait(self.CAPTURE_TIMEOUT):
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 395, in wait
self.stop()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 419, in stop
self._close_output()
File "/usr/lib/python2.7/dist-packages/picamera/encoders.py", line 349, in _close_output
mo.close_stream(output, opened)
File "/usr/lib/python2.7/dist-packages/picamera/mmalobj.py", line 371, in close_stream
stream.flush()
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 238, in flush
self.array = bytes_to_rgb(self.getvalue(), self.size or self.camera.resolution)
File "/usr/lib/python2.7/dist-packages/picamera/array.py", line 127, in bytes_to_rgb
'Incorrect buffer length for resolution %dx%d' % (width, height))
PiCameraValueError: Incorrect buffer length for resolution 640x480
where did it go wrong? I am new to python programming so I get confused about how can I fix it and where to start. Thank you in advance for your answers
Your code doesn't seem to be indented properly. I would suggest indenting these lines:
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
faces = faceCascade.detectMultiScale(
for (x, y, w, h) in faces:
to be indented the same as the line image = frame.array
I think that was the cause of the error since you're supposed to clear the current frame when you're done with it to prepare for the next frame and I see you're trying to do that with rawCapture.truncate(0).
Indentation is really important in python since that's how lines of code are treated as blocks. I see it as how curly braces in some programming languages treat lines of code as blocks.
I think maybe the framerate you set is too high, I delete the line camera.framerate= 32,then the camera window showed in screen.

OpenCV, webcam window not opening

I am very new to computer vision and using the OpenCV libraries for some basic functions like opening a window for the camera. I used the code from the OpenCV book I run a code from there. A part is shown below:
def run(self):
"""Run the main loop"""
self._windowManager.createWindow()
while self._windowManager.isWindowCreated:
self._captureManager.enterFrame()
frame = self._captureManager.frame
self._captureManager.exitFrame()
self._windowManager.processEvents()
I get the following error:
'module' object has no attribute 'nameWindow'
And this the line it points to:
139 def createWindow (self):
140 cv2.namedWindow(self._windowName)
--> 141 self._isWindowCreated = True
142 def show(self, frame):
143 cv2.imshow(self._windowName, frame)
Can someone help me what's going on?
It's hard to say from the code what the problem is, but I believe is cv2.namedWindow()not nameWindow. Also, add cv2.waitKey(1) after the imshow() function call.
Here's a simpler way to open the webcam using python and opencv:
import cv2
video_capture = cv2.VideoCapture(0)
cv2.namedWindow("Window")
while True:
ret, frame = video_capture.read()
cv2.imshow("Window", frame)
#This breaks on 'q' key
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

How to overcome Python fonts (Pygame) not being loaded

I have moved on to messing with Pygame recently, and I started following tutorials. Everything has ran fine up until I reached a program that looks like so:
"""
A python graphics introduction.
This simple program draws lines at a 45 degree angle from one side
of the screen to the other.
"""
# Import a library of functions called 'pygame'
import pygame
from pygame import font
# Initialize the game engine
pygame.init()
# Set the height and width of the screen
size = (400, 500)
screen = pygame.display.set_mode(size)
pygame.display.set_caption("Intro to Graphics")
#Loop until the user clicks the close button.
done = False
clock = pygame.time.Clock()
# Loop as long as done == False
while not done:
for event in pygame.event.get(): # User did something
if event.type == pygame.QUIT: # If user clicked close
done = True # Flag that we are done so we exit this loop
# All drawing code happens after the for loop and but
# inside the main while not done loop.
# Clear the screen and set the screen background
screen.fill(WHITE)
# Select the font to use, size, bold, italics
font = pygame.font.SysFont('Calibri', 25, True, False)
# Render the text. "True" means anti-aliased text.
# Black is the color. This creates an image of the
# letters, but does not put it on the screen
text = font.render("My text", True, BLACK)
# Put the image of the text on the screen at 250x250
screen.blit(text, [250, 250])
# Go ahead and update the screen with what we've drawn.
# This MUST happen after all the other drawing commands.
pygame.display.flip()
# This limits the while loop to a max of 60 times per second.
# Leave this out and we will use all CPU we can.
clock.tick(60)
# Be IDLE friendly
pygame.quit()
When ran I get an error at font = pygame.font.SysFont('Calibri', 25, True, False) that looks like:
RuntimeWarning: use font: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
pygame.font.init()
Traceback (most recent call last):
File "IntroGraphics.py", line 15, in <module>
pygame.font.init()
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/__init__.py", line 70, in __getattr__
raise NotImplementedError(MissingPygameModule)
NotImplementedError: font module not available
(ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/pygame/font.so, 2): Library not loaded: /usr/X11/lib/libfreetype.6.dylib
Referenced from: /Library/Frameworks/SDL_ttf.framework/Versions/A/SDL_ttf
Reason: image not found)
I have looked on here for an answer, and the only other post about it involves 32-bit Pygame with 64-bit Python. I have made sure both of them are running 32-bit (Despite the fact it's a 64-bit machine. Pygame is only 32-bit.). I am running Python 2.7.9 Fresh Install
Other places say it's a problem with SDL, but I am inexperienced with SDL and I wouldn't know what to do.
Has anyone else had this problem?
The fonts that are available to pygame might be different on different computers. I suggest seeing if the font you want to use is included on your computer. You can see the all the available fonts with this command:
pygame.font.get_fonts()
# returns a list of available fonts
You can also get the system's default fort by using this command:
pygame.font.get_default_font()
# returnes the name of the default font
You can use this code to check your font:
if 'Calibri' in pygame.font.get_fonts():
font_name = 'Calibri'
else:
font_name = pygame.font.get_default_font()