Loading an image using Pyglet - opengl

I am playing around with pyglet 1.2alpha-1 and Python 3.3. I have the following (extremely simple) application and cannot figure out what my issue is:
import pyglet
window = pyglet.window.Window()
#image = pyglet.resource.image('img1.jpg')
image = pyglet.image.load('img1.jpg')
label = pyglet.text.Label('Hello, World!!',
font_name='Times New Roman',
font_size=36,
x=window.width//2, y=window.height//2,
anchor_x='center', anchor_y='center')
#window.event
def on_draw():
window.clear()
label.draw()
# image.blit(0,0)
pyglet.app.run()
With the above code, my text label will appear as long as image.blit(0, 0) is commented out. However, if I try to display the image, the program crashes with the following error:
File "C:\Python33\lib\site-packages\pyglet\gl\lib.py", line 105, in errcheck
raise GLException(msg)
pyglet.gl.lib.GLException: b'invalid value'
I also get the above error if I try to use pyglet.resource.image instead of pyglet.image.load (the image and py file are in the same directory).
Any one know how I can fix this issue?
I am using Python 3.3, pyglet 1.2alpha-1, and Windows 8.

The code -including the image.blit- runs fine for me. I'm using python 2.7.3, pyglet 1.1.4
There's nothing wrong with the code. You might consider trying other python and pyglet versions for the time being (until pyglet has a new stable release)

This isn't a "fix", but might at least determine if it's fixable or not (mine was not). (From the Pyglet mailing group.)
You can verify whether the system does not even support Textures greater than 1024, by running this code (Python 3+):
from ctypes import c_long
from pyglet.gl import glGetIntegerv, GL_MAX_TEXTURE_SIZE
i = c_long()
glGetIntegerv(GL_MAX_TEXTURE_SIZE, i)
print (i) # output: c_long(1024) (or higher)
That is the maximum texture size your system supports. If it's 1024, then any larger pictures will raise an Exception. (And the only fix is, get a better system).

Related

set_glue_version exception after upgrading aws-glue-sessions

Using interactive Glue Sessions in a Jupyter Notebook was working correctly with the aws-glue-sessions package version 0.32 installed. After upgrading with pip3 install --upgrade jupyter boto3 aws-glue-sessions to version 0.35, the kernel would not start. Gave an error message in GlueKernel.py line 443 in set_glue_version Exception: Valid Glue versions are {'3.0', '2,0} and the Kernel won't start.
Reverting to version 0.32 resolves the issue. Tried installing 0.35, 0.34, 0.33 and get the error, which makes me think it's something I'm doing wrong or don't understand and not something in the product. Is there anything additional I need to do to upgrade the version of the aws-glue-sessions?
Obviously this is not a good workaround - but it worked for me.
I went into the file GlueKernel.py in the directory: \site-packages\aws_glue_interactive_sessions_kernel\glue_pyspark
and hard-coded the 2nd line of this function to set the version to "3.0"
I'm on windows
def set_glue_version(self, glue_version):
glue_version = str("3.0")
if glue_version not in VALID_GLUE_VERSIONS:
raise Exception(f"Valid Glue versions are {VALID_GLUE_VERSIONS}")
self.glue_version = glue_version
I am a bit lost here as well -- and confused. I will add that I am a python newbie. I am running the whole thing on Windows. AWS has an article that describes the installation. So, I am assuming it's supported. I get the same error as #theOtherOne.
line 443 in set_glue_version Exception: Valid Glue versions are {'3.0', '2,0}
I checked GlueKernel.py of glue_pyspark, and found this code:
def _retrieve_os_env_variable(self, key):
_, output = subprocess.getstatusoutput(f"echo ${key}")
return output or os.environ.get(key)
When I run the code below manually, I get $GLUE_VERSION as final result. That obviously doesn't match '2.0' or '3.0'. The command for retrieving environment variables on Windows is a different one. If my understanding is correct, then this whole thing will never work on Windows. Maybe I am the only one who wants to run it on Windows and no one else cares? I got it to work on WSL, but still. I lost quite some time to fix something that cannot be fixed (or can it?)
import subprocess
import os
_, output = subprocess.getstatusoutput(f"echo $GLUE_VERSION")
osoutput = os.environ.get("GLUE_VERSION")
print(output) #$GLUE_VERSION
print (osoutput) #'3.0'
print(output or osoutput) #$GLUE_VERSION
enter image description here
So the issue seems to be that GLUE_VERSION is not set in the environment variables. Once this is set - it works

Tkinter icon configuration error with Python 2.7

I try to change the ugly Tkinter logo, at top left, follow the documentation, however I get error.
Probably is trivial trouble or related with Python version, mine is 2.7.
But the interesting thing is if you run first without change icon, and after run the script bellow it change without trouble, however if you run the script at first time give the follow error:
TclError: bitmap "C:\Program Files\Anaconda2\DLLs\sca.ico" not defined
My script:
from Tkinter import *
root = Tk()
root.iconbitmap(r'C:\Program Files\Anaconda2\DLLs\sca.ico')
root.mainloop()
My new icon is in this path: C:\Program Files\Anaconda2\DLLs\sca.ico'
Change root.iconbitmap(C:\Program Files\Anaconda2\DLLs\sca.ico) to root.wm_iconbitmap(C:\Program Files\Anaconda2\DLLs\sca.ico) and it might work.
I guess you need to use string as parameter:
root.iconbitmap(r'C:\Program Files\Anaconda2\DLLs\sca.ico')
If you get error _tkinter.TclError: error reading bitmap file use XBM format instead of ICO.
For Linux (worked for me) you need add also '#' at the begin of string:
app_icon = '/home/user/icons/number-three_66512.XBM'
root.iconbitmap('#' + app_icon)

Python speech recognition for Raspberry Pi 2

I am trying to find a Speech recognition library similar to PySpeech that will work on a Raspberry Pi 2. I am new to this and have tried researching but there are so many applications I just need help choosing the correct one.
All I am trying to do is, when a user says something the program will recognize keywords and open up the correct part of my code which will just display information about that keyword.
Right now I am using Python 2.7 and PyQt4 to display what I want but am willing to change if there is something easier such as KivyPi, PyGame, etc.
I am up for any ideas or any help to push me into the right direction.
Thank You!
I created a library called SpeakPython that helps Python developers do exactly this, and just released it under GPL3. The library is built upon pocketsphinx (sphinxbase) and gstreamer (for streaming recognition, which leads to fast results). It will allow you to attach python code to speech commands.
It's very accurate and dynamic for command parsing such as this, and I've tested it on the Pi already. Let me know if you have any issues.
To recognize few words on Raspberry Pi 2 with Python you can use Python bindings to Pocketsphinx
You can find pocketsphinx tutorial to get started here.
You can find some installation details for RPi here.
You can find code example here.
You can find already functioning example using pocketsphinx and python here.
Here is what I have up and running on my pi, it uses python speech recognition, pyaudio and pythons espeak for voice response (if you want that, if not just take it out) this will listen for voice input, print it to text and speak it back to you.. You can manipulate this to do whatever you want basically -
import pyaudio
from subprocess import call
import speech_recognition
r = sr.Recognizer()
r.energy_threshold=4000
with sr.Microphone(device_index = 2, sample_rate = 44100, chunk_size = 512) as source:
print 'listening..'
audio = r.listen(source)
print 'processing'
try:
message = (r.recognize_google(audio, language = 'en-us', show_all=False))
call(["espeak", message])
except:
call(['espeak', 'Could not understand you'])

cv2.imread always returns NoneType

cv2.imread is always returning NoneType.
I am using python version 2.7 and OpenCV 2.4.6 on 64 bit Windows 7.
Maybe it's some kind of bug or permissions issue because the exact same installation of python and cv2 packages in another computer works correctly. Here's the code:
im = cv2.imread("D:\testdata\some.tif",CV_LOAD_IMAGE_COLOR)
I downloaded OpenCV from http://www.lfd.uci.edu/~gohlke/pythonlibs/#opencv. Any clue would be appreciated.
First, make sure the path is valid, not containing any single backslashes. Check the other answers, e.g. https://stackoverflow.com/a/26954461/463796.
If the path is fixed but the image is still not loading, it might indeed be an OpenCV bug that is not resolved yet, as of 2013. cv2.imread is not working properly under Win32 for me either.
In the meantime, use LoadImage, which should work fine.
im = cv2.cv.LoadImage("D:/testdata/some.tif", CV_LOAD_IMAGE_COLOR)
In my case the problem was the spaces in the path. After I moved the images to a path with no spaces it worked.
Try changing the direction of the slashes
im = cv2.imread("D:/testdata/some.tif",CV_LOAD_IMAGE_COLOR)
or add r to the begining of the string
im = cv2.imread(r"D:\testdata\some.tif",CV_LOAD_IMAGE_COLOR)
I also met the same issue before on ubuntu 18.04.
cv2.imread(path)
I solved it when I changed the path argument from Relative_File_Path to Absolute_File_Path.
Hope it be useful.
just stumbled upon this one.
The solution is very simple but not intuitive.
if you use relative paths, you can use either '\' or '/' as in test\pic.jpg or test/pic.jpg respectively
if you use absolute paths, you should only use '/' as in /.../test/pic.jpg for unix or C:/.../test/pic.jpg for windows
to be on the safe side, just use for root, _, files in os.walk(<path>): in combination with abs_path = os.path.join(root, file). Calling imread afterwards, as in img = ocv.imread(abs_path) is always going to work.
In case no one mentioned in this question, another way to workaround is using plt to read image, then convert it to BGR format.
img=plt.imread(img_path)
print(img.shape)
img=img[...,::-1]
it has been mentioned in
cv2.imread does not read jpg files
This took a long time to resolve. first make sure that the file is in the directory and check that even though windows explorer says the file is "JPEG" it is actually "JPG". The first print statement is key to making sure that the file actually exists. I am a total beginner, so if the code sucks, so be it.
The code, just imports a picture and displays it . If the code finds the file, then True will be printed in the python window.
import cv2
import sys
import numpy as np
import os
image_path= "C:/python27/test_image.jpg"
print os.path.exists(image_path)
CV_LOAD_IMAGE_COLOR = 1 # set flag to 1 to give colour image
CV_LOAD_IMAGE_COLOR = 0 # set flag to 0 to give a grayscale one
img = cv2.imread(image_path,CV_LOAD_IMAGE_COLOR)
print img.shape
cv2.namedWindow('Display Window') ## create window for display
cv2.imshow('Display Window', img) ## Show image in the window
cv2.waitKey(0) ## Wait for keystroke
cv2.destroyAllWindows() ## Destroy all windows
I had a similar problem, changing the name of the image to English alphabetic worked for me. Also, it didn't work with a numeric name (e.g. 1.jpg).
My OS is Windows 10. I noticed imread is very sensitive to path. No any recommendation about slashes worked for me, so how I managed to solve problem: I have placed file to project folder and typed:
img = cv2.imread("MyImageName.jpg", 0)
So without any path and folder, just file name. And that worked for me.
Also try different files from different sources and of different formats
I spent some time on this only to find that this error is caused by a broken image file on my case. So please manually check your file to make sure it is valid and can be opened by common image viewers.
I had a similar issue,changing direction of slashes worked:
Change / to \
In my case helped changing file names to latin alphabet.
Instead of renaiming all files I wrote a simple wrapper to rename a file before the load into a random guid and right after the load rename it back.
import os
import uuid
import cv2
uid = str(uuid.uuid4())
def wrap_file_rename(my_path, function):
try:
directory = os.path.dirname(my_path)
new_full_name = os.path.join(directory, uid)
os.rename(my_path, new_full_name)
return function(new_full_name)
except Exception as error:
logger.error(error) # use your logger here
finally:
os.rename(new_full_name, my_path)
def my_image_read(my_path, param=None):
return wrap_file_rename(my_path, lambda p: cv2.imread(p) if param is None else cv2.imread(p, param))
Sometimes the file is corrupted. If it exists and cv2.imread returns None this may be the case.
Try opening the file כfrom file explorer and see if that works
I've run into this. Turns out the PIL module provides this functionality.
Similarly, numpy.imread and scipy.misc.imread both didn't exist until I installed PIL
In my configuration (win7 python2.7), that was done as follows:
cd /c/python27/scripts
easy_install PIL

View a sequence of images using Python and NumPy

I am using python's pil library to display images. Now I have a sequence of frames to display as a video content. I have a np.array that contains the RGB values of all the frames.
Could not find a method similar to Mathlabs implay to display these frames.
I can use imshow in a loop, but thats would be very slow as I need to mention framerate.
Matplotlib animations work well, and is easy to use. For reasonable size images they typically run at 30fps, or around that. Matplotlib 1.1+ has a nice new animation interface: here are some examples and a tutorial.
Older versions of matplotlib aren't to hard to animate either (you basically just set the data directly and refresh the plot) but the animation depends a bit more on the backend, so you need to look for an appropriate example.
For a specific example, if images is your list of matplotlib images that you want to animate, you can simply do:
animation.ArtistAnimation(fig, images, interval=50, blit=True, repeat_delay=1000)
This, btw, is taken from this example, if you want to also see the code that generates test images. The code to animate is simply the line above.
I have implemented a handy script that just suits your need. Try it out here
An example to show lists of images in a directory will be
import os
import glob
from scipy.misc import imread
img_dir = 'YOUR-IMAGE-DIRECTORY'
img_files = glob.glob(os.path.join(video_dir, '*.jpg'))
def redraw_fn(f, axes):
img_file = img_files[f]
img = imread(img_file)
if not redraw_fn.initialized:
redraw_fn.im = axes.imshow(img, animated=True)
redraw_fn.initialized = True
else:
redraw_fn.im.set_array(img)
redraw_fn.initialized = False
videofig(len(img_files), redraw_fn, play_fps=30)
If you happen to already have a working OpenCV install built with OpenEXR – which if you don’t, it’s at least as much of an irritating time-sink to rebuild OpenCV as e.g. compiling SciPy from source in the first place – but so if the library is already there and working, you can use the Python bindings to quickly† view images with only a little bit of boilerplate. From this example:
import OpenEXR, Imath, cv
filename = "GoldenGate.exr"
exrimage = OpenEXR.InputFile(filename)
dw = exrimage.header()['dataWindow']
(width, height) = (dw.max.x - dw.min.x + 1, dw.max.y - dw.min.y + 1)
def fromstr(s):
mat = cv.CreateMat(height, width, cv.CV_32FC1)
cv.SetData(mat, s)
return mat
pt = Imath.PixelType(Imath.PixelType.FLOAT)
(r, g, b) = [fromstr(s) for s in exrimage.channels("RGB", pt)]
bgr = cv.CreateMat(height, width, cv.CV_32FC3)
cv.Merge(b, g, r, None, bgr)
cv.ShowImage(filename, bgr)
cv.WaitKey()
I believe the OpenCV matrix type implements the python interfaces for memoryview et al – don’t be scared off by those objects as they’re NumPy arrays with different socks on, if you will.
†) quickly, w/r/t both the developer sense of speed: you can use this stuff immediately instead of building SciPy addons or mucking about with the Python array view C interface; but also in the real sense, as everything that comprises the aforementioned stuff – the OpenCV matrix structs, their related Python C API underpinnings, the OpenEXR format, and the stock implementation of the interface to same – have been raked over the optimization coals for years, largely by notable and grant-backed squadrons of specialist scholar-nerds who know what they are doing in this arena.