How to overcome Python fonts (Pygame) not being loaded - python-2.7

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

Related

What is wrong with my python 2 code that incorporates a wii remote that activates a buzzer via GPIO on a raspberry pi zero w?

Here is my python code that I am using. I am trying to use a wii remote to trigger a buzzer. I thought this would be an interesting use for my old wii remote. The code that interacts with the buzzer works fine because I used an example script to test it. However, when I try and run it I keep getting this one error (see bottom). I am new to python and would appreciate any help.
import cwiid
from gpiozero import LED
import time
import os
Buzzer1 = LED(17)
Buzzer2 = LED(27)
def ConnectRemote():
os.system("rfkill unblock bluetooth")
print 'Press 1+2 On The Remote...'
global wm
wm = wiid.Wiimote()
print 'Connection Established!\n'
wm.led = 1
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
time.sleep(0.5)
wm.rpt_mode = cwiid.RPT_BTN
def TryToConnect():
while True:
ConnectRemote()
break
while True:
buttons = wm.state['buttons']
#shutdown function using plus and minus buttons
if (buttons - cwiid.BTN_PLUS - cwiid.BTN_MINUS == 0):
print '\nClosing Connection To Wiimote'
wm.rumble = 1
time.sleep(0.25)
wm.rumble = 0
os.system("rfkill block bluetooth")
TryToConnect()
if (buttons & cwiid.BTN_A):
print 'Buzzer On'
Buzzer1.on()
Buzzer2.on()
else:
Buzzer1.off()
Buzzer2.off()
and yet I keep getting an error of
Traceback (most recent call last):
File "WiimoteLEDs.py", line 36, in <module>
buttons = wm.state['buttons']
NameError: global name 'wm' is not defined
Can anyone help? Thanks in advance
I think you should initialized variable wm before using this variable in function.
This bug is related to 'Global name not defined'

How detect if an image can paste a background?

I'm trying convert images in Pillow==5.4.1 to JPEG. So i use this follow code:
from PIL import Image as PilImage
img = PilImage.open('energy.png')
img.convert('RGB').save('newimage.jpeg', 'jpeg')
Some images works fine, but when i try if this image:
My result is follow:
OK, i have a problem, when a image have transparency, the background turn black. So i research and follow this code:
PIL Convert PNG or GIF with Transparency to JPG without
from PIL import Image
im = Image.open("energy.png")
bg = Image.new("RGB", im.size, (255,255,255))
bg.paste(im,im)
bg.save("newimage.jpeg")
This works fine for this picture:
The background turn white, no problem i can survive with it. But when i use this code for other images:
In [28]: im = Image.open('444.png')
In [29]: bg = Image.new("RGB", im.size, (255,255,255))
In [30]: bg.paste(im,im)
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-30-f36dbc2a3949> in <module>()
----> 1 bg.paste(im,im)
/home/developer/.virtualenvs/prisvo/local/lib/python2.7/site-packages/PIL/Image.pyc in paste(self, im, box, mask)
1455 if mask:
1456 mask.load()
-> 1457 self.im.paste(im, box, mask.im)
1458 else:
1459 self.im.paste(im, box)
ValueError: bad transparency mask
This error occur with this two images:
One of this two images is png (with no transparency), and the other is already jpeg, but i need to accept jpg and png. Because i need to do this:
img.convert('RGB').save(smallJpegThumbStr, 'jpeg', quality=75)
I need to compact.
So i use (and i think) a bad implementation:
try:
bg = PilImage.new("RGB", img.size, (255,255,255))
bg.paste(img,mask=img)
bg.convert('RGB').save(mediumJpegThumbStr, 'jpeg', quality=75)
except:
img.convert('RGB').save(mediumJpegThumbStr, 'jpeg', quality=75)
In others words, when occur a error i go to another implementation. I think this is not right. My first idea is use the first implementation (inside expect) to jpeg images, and second implementation to png (inside try). But the error also occur to png (for some images). I dont know if is there a condition for this command bg.paste(im,im), or if exist an way to detect this error: ValueError: bad transparency mask without using try.
This command help. But:
bg.paste(im,mask=im.convert('L'))

OpenCV video writer writes blank files due to memory leak?

I'm trying to save video files on a raspberry pi with python2.7 and opencv. The code shown below consistently saves several video files (size 16-18 Mb) to a usb but after the first few files the file sizes drop to 6 kb and appear to be empty since they won't open.
I opened task manager to monitor the memory usage by python during the saving and noticed that the RSS memory continually increases until roughly 200 MB which is when the video files start showing up blank.
Is that a sure indicator of a memory leak, or should I run other tests?
Is there something wrong in the below code that isn't releasing variables properly?
import cv2
import numpy as np
import datetime
dispWidth = 640
dispHeight = 480
FPS = 6
SetupNewVideoFile = True # state variable
VidCaptureDurationMinutes = 3
filepath = '/media/pi/9CEE-5383/Videos/'
i = 1 # counter for the video file names
fourcc = cv2.cv.CV_FOURCC('X','V','I','D')
while True:
# timer section that ends running file saves and triggers a new file save
Now = datetime.datetime.now() # refresh current time
delta = Now - VidCaptureStartTime
print('delta: ',delta.seconds,delta.days)
if ((delta.seconds/60) >= VidCaptureDurationMinutes) and delta.days >= 0:
print('delta: ',delta.seconds,delta.days)
SetupNewVideoFile = True
Vidoutput.release()
cap.release()
# setting up new file saves
if SetupNewVideoFile:
SetupNewVideoFile = False
title = "Video_"+str(i)+".avi"
i += 1
fullpath = filepath + title
print(fullpath)
Vidoutput = cv2.VideoWriter(fullpath, fourcc, FPS,(dispWidth,dispHeight))
VidCaptureStartTime = datetime.datetime.now() # updating video start time
cap = cv2.VideoCapture(-1) # start video capture
ret, frame = cap.read()
if ret: # display and save if a frame was successfully read
cv2.imshow('webcam',frame)
Vidoutput.write(frame) # save the frames
key = cv2.waitKey(1) & 0xFF
if key == ord('q'): # quits program
break
# clean up
cap.release()
Vidoutput.release()
cv2.destroyAllWindows()
cv2.waitKey(1) # these seem to be needed to flush the cv actions
cv2.waitKey(1)
cv2.waitKey(1)
cv2.waitKey(1)
After some more trouble shooting and help from the pympler module functions and tutorials (https://pythonhosted.org/Pympler/muppy.html) my problems still looked like a memory leak but I was unable to solve the specific error.
This other S.O. post (Releasing memory in Python) mentioned improvements in memory management made in version 3.3 of Python:
"In Python 3.3 the small object allocator was switched to using anonymous memory maps instead of the heap, so it should perform better at releasing memory."
So I switched over to Python 3.3 and now the code saves valid video files well past the error out time I saw previously.
This isn't an answer as to why the blank files were occurring, but at least it's a solution.

pygame program exits with no error message when run with pythonw

I'm trying to run a pygame program using pythonw to avoid having the console window show up. This causes a weird issue related to print statements.
Basically, the program will just exit after a few seconds with no error message. The more printing I do, the faster it happens.
If I run it in idle or at the command prompt (or in linux) the program works fine. This problem only happens when launched with pythonw (right-click, Open With, pythonw).
I'm using python 2.7.11 on Windows XP 32-bit. pygame 1.9.1release.
Is there a workaround for this? Why does the program simply terminate with no error?
import pygame
from pygame.locals import *
succeeded, failed = pygame.init()
display_surface = pygame.display.set_mode((320, 240))
clock = pygame.time.Clock()
terminate = False
while terminate is False:
for event in pygame.event.get():
if event.type == QUIT:
terminate = True
area = display_surface.fill((0,100,0))
pygame.display.flip()
elapsed = clock.tick(20)
print str(elapsed)*20
pygame.quit()
You don't need to remove print statements. Save them for later debugging. ;-)
Two steps to solve this problem:
Firstly, keep all the code in py file - don't change it to pyw now; Say it is actualCode.py
Then, create a new file runAs.pyw with the following lines in it
# In runAs.pyw file, we will first send stdout to StringIO so that it is not printed
import sys # access to stdout
import StringIO # StringIO implements a file like class without the need of disc
sys.stdout = StringIO.StringIO() # sends stdout to StringIO (not printed anymore)
import actualCode # or whatever the name of your file is, see further details below
Note that, just importing actualCode runs the file, so, in actualCode.py you should not enclose the code which is executed, in what I call is it main running file condition. For example,
# In actualCode.py file
....
....
....
if __name__ == '__main__': # Don't use this condition; it evaluates to false when imported
... # These lines won't be executed when this file is imported,
... # So, keep these lines outside
# Note: The file in your question, as it is, is fine

pygame initialize framebuffer or x server

I have a class that checks for suitable framebuffer, and it works fine. One a couple of computers (mostly embedded older boards) there is no framebuffer, so I remove the init(self): function and manually set it to run under X. Both ways work on their respective systems, I'm just tired of porting it every time I make a change.
Here is the working framebuffer code:
class wxdisplay :
screen = None;
def __init__(self):
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)class wxdisplay :
And here is the non-framebuffered version:
class wxdisplay :
pygame.init()
size = (1024, 768)
screen = pygame.display.set_mode(size)
print "Framebuffer size: %d x %d" % (size[0], size[1])
I would like to try and initialize the framebuffer and if it fails, try and just run it on the console. Every thing I have try'd or if'd or excepted fails...
class wxdisplay :
def __init__(self):
# Try to use framebuffer, and use the local X server if not there
try:
screen = None;
"Ininitializes a new pygame screen using the framebuffer"
# Based on "Python GUI in Linux frame buffer"
# http://www.karoltomala.com/blog/?p=679
disp_no = os.getenv("DISPLAY")
print("disp_no " +disp_no)
if disp_no:
print "I'm running under X display = {0}".format(disp_no)
# Check which frame buffer drivers are available
# Start with fbcon since directfb hangs with composite output
drivers = ['fbcon', 'directfb', 'svgalib', 'xvfb', 'Xvfb']
found = False
for driver in drivers:
# Make sure that SDL_VIDEODRIVER is set
if not os.getenv('SDL_VIDEODRIVER'):
os.putenv('SDL_VIDEODRIVER', driver)
try:
print("Driver: "+driver)
pygame.display.init()
except pygame.error:
print 'Driver: {0} failed.'.format(driver)
continue
found = True
print("break")
break
if not found:
raise Exception('No suitable video driver found!')
size = (pygame.display.Info().current_w, pygame.display.Info().current_h)
print "Framebuffer size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size, pygame.FULLSCREEN)
except:
print('No suitable Framebuffer found!')
pygame.init()
size = (1024, 768)
print "X server size: %d x %d" % (size[0], size[1])
self.screen = pygame.display.set_mode(size)
fails with:
starting from __main__ call
disp_no localhost:11.0
I'm running under X display = localhost:11.0
Driver: fbcon
Driver: fbcon failed.
Driver: directfb
commandline read: python
commandline read: ./PiWxDisplay.py
~~~~~~~~~~~~~~~~~~~~~~~~~~| DirectFB 1.2.10 |~~~~~~~~~~~~~~~~~~~~~~~~~~
(c) 2001-2008 The world wide DirectFB Open Source Community
(c) 2000-2004 Convergence (integrated media) GmbH
----------------------------------------------------------------
(*) DirectFB/Core: Single Application Core. (2012-05-20 13:17)
(!) Direct/Util: opening '/dev/fb0' and '/dev/fb/0' failed
--> No such file or directory
(!) DirectFB/FBDev: Error opening framebuffer device!
(!) DirectFB/FBDev: Use 'fbdev' option or set FRAMEBUFFER environment variable.
(!) DirectFB/Core: Could not initialize 'system_core' core!
--> Initialization error!
Driver: directfb failed.
Driver: svgalib
Driver: svgalib failed..
No suitable Framebuffer found!
X server size: 1024 x 768
Traceback (most recent call last):
File "./PiWxDisplay.py", line 366, in <module>
wxdisplay().start_screen()
File "./PiWxDisplay.py", line 66, in __init__
self.screen = pygame.display.set_mode(size)
pygame.error: No available video device
I obviously don't fully understand how to initialize pygame correctly. How would I get it to
Check for a FB driver
Use the X server if the FB driver detection fails
Late answer but I wish I would have tried that earlier :
You may need to be root to use a frame buffer driver.
(It helped in my case: RaspberryPi 2 without X running but with a screen connected. I can now open a display through SSH or directly on the RPi)
You have already changed the SDL_VIDEODRIVER environment to check only for fb devices.
I'd suggest using this before your pygame.init() call in your exception handler:
os.putenv('SDL_VIDEODRIVER', 'x11')
or unset the SDL_VIDEODRIVER environment var, so that pygame.init() doesn't think it's already dealt with.
see: http://www.pygame.org/docs/ref/display.html#pygame.display.init