I am wondering why I can get this error:
pyglet.lib.gl.GLExeption: invalid value
at: self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
Imported libs:
import sys
import math
import random
import time
from collections import deque
from pyglet import image
from pyglet.gl import *
from pyglet.graphics import TextureGroup
from pyglet.window import key, mouse, Window
from PIL import Image
I'm using PIL for making the PNG:
print "Creating ", TEXTURE_PATH
images = map(Image.open, texture_path)
widths, heights = zip(*(i.size for i in images))
total_width = sum(widths)
max_height = max(heights)
new_im = Image.new('RGB', (total_width, max_height))
x_offset = 0
for im in images:
new_im.paste(im, (x_offset,0))
x_offset += im.size[0]
new_im.convert('RGB')
new_im.save(TEXTURE_PATH, "PNG")
And the 'texture_path`(lowercase) is here:
texture_path = ['res/textures/grass_top.png'] * 99
The full error message is:
Traceback (most recent call last):
File "D:\pythoncode\pyglet\minecraft_remake.py", line 955, in <module>
main()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 948, in main
window = Window(width = 640, height = 480, caption="Minecraft 3d!", resizable=True)
File "D:\pythoncode\pyglet\minecraft_remake.py", line 554, in __init__
self.model = Model()
File "D:\pythoncode\pyglet\minecraft_remake.py", line 198, in __init__
self.group = TextureGroup(image.load(TEXTURE_PATH).get_texture())
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 818, in get_texture
force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 803, in create_texture
rectangle, force_rectangle)
File "C:\Python27\lib\site-packages\pyglet\image\__init__.py", line 1514, in create
blank)
File "C:\Python27\lib\site-packages\pyglet\gl\lib.py", line 104, in errcheck
raise GLException(msg)
GLException: invalid value
I found the problem, but didn't know how to fix it, the problem are in the PNG making.
When I replace the textures.png with another picture, it's working
but when I make one with PIL, it doesn't work.
Solved: the problem is in my .PNG Editor, i just make the image manually and it works!
im using Graphics Gale Free edition to edit and it will work.
i think the problem is in the PIL itself. Or The pyglet doesnt load PIL config PNG
P.s it may be because color configuration
Related
Hey i am trying to locate an image but get this error on why i use the value as (any,any,250,250) but doesnt show the error when i use(any,any,350(more than 350),250(more than 250))
here is my code
`
from pyautogui import *
import pyautogui
import time
import keyboard
import random
import win32api, win32con
import cv2
import numpy as np
PlayerOnRight = False
PlayerOnFullRight = False
PlayerOnFullLeft = False
PlayerOnLeft = False
PlayerOnMiddle = False
while 1:
if PlayerOnMiddle == True and pyautogui.locateOnScreen('player.png', region=(1080,600,800,200), confidence=0.7) != None:
print("Right Side")
time.sleep(0.5)
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
print("Left Side")
time.sleep(0.5)
`
here is the error
`Traceback (most recent call last):
File "C:\Users\Admin\Desktop\Pyhton_bot\test.py", line 20, in <module>
if pyautogui.locateOnScreen('player.png', region=(825,800,250,250), confidence=0.3) !=None:
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 175, in wrapper
return wrappedFunction(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyautogui\__init__.py", line 213, in locateOnScreen
return pyscreeze.locateOnScreen(*args, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 373, in locateOnScreen
retVal = locate(image, screenshotIm, **kwargs)
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 353, in locate
points = tuple(locateAll(needleImage, haystackImage, **kwargs))
File "C:\Python310\lib\site-packages\pyscreeze\__init__.py", line 219, in _locateAll_opencv
raise ValueError('needle dimension(s) exceed the haystack image or region dimensions')
ValueError: needle dimension(s) exceed the haystack image or region dimensions
`
i expted it to work noramlly to locate image and pint the given text but got this error
please help me fix this
Because the region has to be bigger than your player.png image. Either crop your player.png image or increase the region size
I'm trying to convert a .npy image to a nii.gz image, I'm having various problems even though I'm following instructions correctly.
This is the code I'm using:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
print(img_array1.shape)
print(img_array1.dtype)
normal_array = "D:/teste volumes slicer/teste01.npy"
print ("done")
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
About the image: (332, 360, 360) float64 (this is what we got when we print the shape and dtype)
https://ibb.co/mRyTrw7 - image that shows the error and the image's information
The error message:
Traceback (most recent call last):
File "d:\teste volumes slicer\conversor.py", line 16, in <module>
nifti_file = nib.Nifti1Image(normal_array, np.eye(4))
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1756, in __init__
super(Nifti1Pair, self).__init__(dataobj,
File "C:\Python39\lib\site-packages\nibabel\analyze.py", line 918, in __init__
super(AnalyzeImage, self).__init__(
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 469, in __init__
self.update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 2032, in update_header
super(Nifti1Image, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\nifti1.py", line 1795, in update_header
super(Nifti1Pair, self).update_header()
File "C:\Python39\lib\site-packages\nibabel\spatialimages.py", line 491, in update_header
shape = self._dataobj.shape
AttributeError: 'str' object has no attribute 'shape'
The problem with your code is instead of passing your Numpy-array (your image), you are passing the path of the image to the Nifti1Image function.
This is the correct way to convert it:
import numpy as np
import nibabel as nib
file_dir = "D:/teste volumes slicer/"
fileNPY1 = "teste01.npy"
img_array1 = np.load(file_dir + fileNPY1)
nifti_file = nib.Nifti1Image(img_array1 , np.eye(4))
I'm trying to run the following code,
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
for index,data in enumerate(skeleton):
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
head=data.SkeletonPositions[JointId.Head]
print head
but Kinect shuts down and gives the following error:
Traceback (most recent call last):
File "C:\Users\sayyed javed ahmed\Desktop\Humaira\Practice Codes-Python\skeletonnew.py", line 5, in <module>
with nui.Runtime() as kinect:
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 126, in __init__
self.camera = Camera(self)
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 352, in __init__
self.elevation_angle
File "C:\Python27\lib\site-packages\pykinect\nui\__init__.py", line 359, in get_elevation_angle
return self.runtime._nui.NuiCameraElevationGetAngle()
File "C:\Python27\lib\site-packages\pykinect\nui\_interop.py", line 200, in NuiCameraElevationGetAngle
_NuiInstance._NuiCameraElevationGetAngle(self, ctypes.byref(res))
File "_ctypes/callproc.c", line 950, in GetResult
WindowsError: [Error -2147024883] The data is invalid
I'm new to PyKinect so any help is appreciated! Thanks!
Firstly, there are typos in your code. You're assigning a callback to skeleton_frame_ready function in kinect.skeleton_frame_ready+=skeleton_frame_ready, but have defined it as def skeleton_fram_raedy(skeleton_frame).
Secondly, I think your indentation is off, you have a function definition in a for loop in a while loop:
while True:
frame= kinect.skeleton_engine.get_next_frame()
for skeleton in frame.SkeletonData:
def skeleton_fram_raedy(skeleton_frame):
...
Try something like this:
from pykinect import nui
from pykinect.nui import JointId
from pykinect.nui import SkeletonTrackingState
from pykinect.nui import TransformSmoothParameters
def skeleton_frame_ready(skeleton_frame):
for skeleton in frame.SkeletonData:
if skeleton.eTrackingState==nui.SkeletonTrackingState.TRACKED:
for index,data in enumerate(skeleton):
head=data.SkeletonPositions[JointId.Head]
print head
with nui.Runtime() as kinect:
kinect.skeleton_frame_ready+=skeleton_frame_ready
kinect.skeleton_engine.enable=True
while True:
frame= kinect.skeleton_engine.get_next_frame()
Thirdly, the error indicates that invalid argument is passed to nui for the kinect camera angle. Not sure why that is. You could try setting the elevation angle to 0 right after initializing nui:
with nui.Runtime() as kinect:
kinect.camera.elevation_angle = 0
kinect.skeleton_frame_ready+=skeleton_frame_ready
When I try the following:
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
import urllib
import StringIO
import PIL.Image
image_file = urllib.urlopen('https://www.google.com/images/srpr/logo11w.png')
image_string = StringIO.StringIO(image_file.read())
logo = PIL.Image.open(image_string)
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10)
canvas.showPage()
canvas.save()
I get this error:
Traceback (most recent call last):
File "imagefromurl.py", line 12, in <module>
canvas.drawImage(logo, 10, 10)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfgen/canvas.py", line 857, in drawImage
imgObj = pdfdoc.PDFImageXObject(name, image, mask=mask)
File "/usr/lib/python2.7/dist-packages/reportlab/pdfbase/pdfdoc.py", line 2090, in __init__
ext = string.lower(os.path.splitext(source)[1])
File "/usr/lib/python2.7/posixpath.py", line 96, in splitext
return genericpath._splitext(p, sep, altsep, extsep)
File "/usr/lib/python2.7/genericpath.py", line 91, in _splitext
sepIndex = p.rfind(sep)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 515, in __getattr__
raise AttributeError(name)
Reportlab is version 2.5.
I was doing it the hard way. This works (also added the necessary mask to avoid transparent becoming black):
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.utils import ImageReader
logo = ImageReader('https://www.google.com/images/srpr/logo11w.png')
canvas = Canvas('output.pdf', pagesize=letter)
canvas.drawImage(logo, 10, 10, mask='auto')
canvas.showPage()
canvas.save()
Though the hard way would have allowed me to detect a failure to fetch the image url and handle it (e.g. substituting a local image), and this doesn't.
I am working on a python program that displays a series of images using Tkinter and ImageTk. I have not been able to display more than a single image. Below is a small complete program that reproduces the error. The program searches the current directly recursively for jpg files, and displays them as the uses presses Enter.
import Tkinter, ImageTk,os, re
def ls_rec(direc):
try:
ls = os.listdir(direc)
except Exception as e:
return
for f in os.listdir(direc):
fpath = os.path.join(direc, f)
if os.path.isfile(fpath):
yield fpath
elif os.path.isdir(fpath):
for f2 in iterate_dir(os.path.join(direc,f)):
yield f2
images = filter(lambda a:re.match('.*\\.jpg$',a),ls_rec(os.getcwd()))
assert(len(images)>10)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
Label_text = Tkinter.Label(top,text="Below is an image")
img = None
i = 0
def get_next_image(event = None):
global i, img
i+=1
img = ImageTk.PhotoImage(images[i])
label.config(image=img)
label.image = img
top.bind('<Enter>',get_next_image)
label.pack(side='bottom')
Label_text.pack(side='top')
get_next_image()
top.mainloop()
The program fails with the following traceback:
Traceback (most recent call last):
File "/usr/lib/python2.7/pdb.py", line 1314, in main
pdb._runscript(mainpyfile)
File "/usr/lib/python2.7/pdb.py", line 1233, in _runscript
self.run(statement)
File "/usr/lib/python2.7/bdb.py", line 387, in run
exec cmd in globals, locals
File "<string>", line 1, in <module>
File "/home/myuser/Projects/sample_images.py", line 1, in <module>
import Tkinter, ImageTk,os, re
File "/home/myuser/Projects/sample_images.py", line 32, in get_next_image
img = ImageTk.PhotoImage(some_image[1])
File "/usr/lib/python2.7/dist-packages/PIL/ImageTk.py", line 109, in __init__
mode = Image.getmodebase(mode)
File "/usr/lib/python2.7/dist-packages/PIL/Image.py", line 245, in getmodebase
return ImageMode.getmode(mode).basemode
File "/usr/lib/python2.7/dist-packages/PIL/ImageMode.py", line 50, in getmode
return _modes[mode]
KeyError: '/home/myuser/sampleimage.jpg'
Does anyone get the same behavior when running this code? What am I doing wrong?
EDIT: Using korylprince's solution, and a bit of cleaning, the following is a working version of the original code:
import os, re, Tkinter, ImageTk
def ls_rec(direc, filter_fun=lambda a:True):
for (dirname, dirnames, fnames) in os.walk(direc):
for fname in fnames:
if filter_fun(fname):
yield os.path.join(dirname,fname)
top = Tkinter.Tk()
image_label = Tkinter.Label(top)
text_label = Tkinter.Label(top,text="Below is an image")
images = ls_rec(os.getcwd(), lambda a:re.match('.*\\.jpg$',a))
imgL = []
def get_next_image(event = None):
fname = images.next()
print fname
fhandle = open(fname)
img = ImageTk.PhotoImage(file=fhandle)
fhandle.close()
imgL.append(img)
image_label.config(image=img)
top.bind('<Return>',get_next_image)
image_label.pack(side='bottom')
text_label.pack(side='top')
get_next_image()
top.mainloop()
Edit: top.bind('<Enter>'...) actually bound the event of the mouse entering the frame, rather than user pressing Enter key. The correct line is top.bind('<Return>',...).
ImageTk.PhotoImage is not really documented properly.
You should try something like this:
#outside of functions
images = list()
#inside function
global images
with open(images[i]) as f:
img = ImageTk.PhotoImage(file=f)
images.append(img)
The reason for putting the image in the list is so that python will have a reference to it. Otherwise the garbage collector will delete the image object eventually.