Python Cocos2d can't find resource image after resizing it - python

I'm trying to resize an image in Python and then load a cocos2d sprite with the resized image. However, trying to initialize a cocos2d sprite results in an error that the resource can't be found. Example code to reproduce the problem:
from pathlib import Path
import cocos
from PIL import Image
im = Image.open("in.jpg")
im.thumbnail((600, 900))
im.save("out.jpg", "JPEG")
im.close()
file = Path("out.jpg")
if file.is_file():
print("File exists")
sprite = cocos.sprite.Sprite("out.jpg")
This results in the error
pyglet.resource.ResourceNotFoundException: Resource "out.jpg" was not found on the path. Ensure that the filename has the correct captialisation.
However, the output is:
File exists
Running it a second time doesn't give errors, since out.jpg has been created in the previous run. Deleting out.jpg and running it again produces the error.
Adding an im.close() didn't solve the problem.
The OS is Windows 10 with Python version 3.6.4.

It turned out to be the method used in pyglet to load a resource. I had to reindex the images. The files in the images directory where dynamically added and pyglet creates an index of existing images. See https://stackoverflow.com/a/16438410/6350693 for the answer.

Related

PyQt5 - fromIccProfile: failed minimal tag size sanity error

I'm using latest PyQt5 5.12.2 and I'm getting a weird message for every JPG picture that I'm showing in my script using QPixmap or QIcon.
qt.gui.icc: fromIccProfile: failed minimal tag size sanity
It isn't causing anything and the script works as it should. The problem is that I'm trying to display a huge amount of jpg pictures at the same time (as a photo gallery) so the window gets unresponsive until all messages are printed for each photo.
I tried for hours to find something useful online but unfortunately, it seems like nearly no one had the same issue. I'm using some PNG files too and they don't raise this error so I'm assuming that the problem is with jpg format. I tried using older pyqt5 versions but the only difference is that they are not printing the message but the problem remains.
Meanwhile, I tried to use this command to mute those messages since there is no use of them but the problem with unresponsive window for a few seconds remains even when it's not printing in the console.
def handler(*args):
pass
qInstallMessageHandler(handler)
EDIT: I tried converting these images to PNG but the error remains. So the JPG format wasn't the problem
I dug more deeply into ICC profiles and colour spaces and it seems like the colour space that your pictures are using is somehow non-standard for PyQt.
My solution is to convert these pictures to an ICC profile that is classical such as sRGB.
Here's an example function:
import io
from PIL import Image, ImageCms
def convert_to_srgb(file_path):
'''Convert PIL image to sRGB color space (if possible)'''
img = Image.open(file_path)
icc = img.info.get('icc_profile', '')
if icc:
io_handle = io.BytesIO(icc) # virtual file
src_profile = ImageCms.ImageCmsProfile(io_handle)
dst_profile = ImageCms.createProfile('sRGB')
img_conv = ImageCms.profileToProfile(img, src_profile, dst_profile)
icc_conv = img_conv.info.get('icc_profile','')
if icc != icc_conv:
# ICC profile was changed -> save converted file
img_conv.save(file_path,
format = 'JPEG',
quality = 50,
icc_profile = icc_conv)
Using PIL library is a fast and effective way how to properly resolve that error.
I am making a GUI Image Viewer with Pyside2 and was having a similar issue.
The images were loading fine and for my case there was no performances issues, but I keep getting these ICC warnings.
And I didn't want to fix the original files, because my app is supposed to be only a viewer.
I don't know it will help for your case, but my solution is to first load the image with pillow ImageQT module
from pathlib import Path
from PIL.ImageQt import ImageQt
def load_image(path):
if Path(path).is_file():
return ImageQt(path)
Then in my QT Widget class that display the image, I load this image on a empty QPixmap:
def on_change(self, path):
pixmap = QtGui.QPixmap()
image = load_image(path)
if image:
pixmap.convertFromImage(image)
if pixmap.isNull():
self.display_area_label.setText('No Image')
else:
self.display_area_label.setPixmap(pixmap)

Error - pygame.error: Couldn't open backround.png. Fix? [duplicate]

This question already has an answer here:
Could not open resource file, pygame error: "FileNotFoundError: No such file or directory."
(1 answer)
Closed 2 years ago.
Im trying to load an image into a window on pygame but when i run the code. It pops up with an error of
pygame.error: Couldn't open backround.png
I have the image in the same folder with the code itself. I have done this for another script and it works perfectly fine. I am not sure what the problem is.
I've tried closing my program. Renaming the file but that's about it. Not sure how to tackle the problem. Any help is much appreciated
import pygame
import os
from Introduction import *
# Making the window
pygame.init()
windowSize = (800, 600)
screen = pygame.display.set_mode(windowSize)
# Images in the Introduction
GameBackround = pygame.image.load('backround.png')
while True:
screen.blit(GameBackround, (0,0))
for event in pygame.event.get():
screen.blit(GameBackround, (0,0))
pygame.display.update()
pygame.display.flip()
Like I said: I have used similar layout to load images with another file and it works perfectly fine but for some reason it doesn't load the image in case.
The image filepath has to be relative to the current working directory. The working directory is possibly different to the directory of the python file.
The name and path of the file can be get by __file__. The current working directory can be get by os.getcwd().
If the image is in the same folder as the python file, then you cnb get the directory of the file and change the working directory by os.chdir(path):
import os
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
os.chdir(sourceFileDir )
or concatenate the image filename and the file path by os.path.join. e.g.:
import pygame
import os
from Introduction import *
# get the directory of this file
sourceFileDir = os.path.dirname(os.path.abspath(__file__))
# [...]
GameBackround = pygame.image.load(os.path.join(sourceFileDir, 'backround.png'))

OpenCV fails to create video from images

This is my first attempt at making a video file and I seem to be very clumsy.
Inspired by these instructions to put several images in a single video, I modified the code by creating a function that can loop through the folder with the images. But it is taking too long. I thought it was because there are many images, but even if I only use two images to do it, it still runs forever.
I get no error message, the script just never stops.
Could anybody please explain what is wrong with my code? There must be something silly which I didn't spot and is making it an infinite loop or something...
import cv2
import os
forexample = "C:/Users/me/Pictures/eg/"
eg = cv2.imread(forexample+'figure.jpg')
height , width , layers = eg.shape
print "ok, got that"
def makeVideo(imgPath, videodir, videoname, width,height):
for img in os.listdir(imgPath):
video = cv2.VideoWriter(videodir+videoname,-1,1,(width,height))
shot = cv2.imread(img)
video.write(shot)
print "one video done"
myexample = makeVideo(forexample,forexample, "example.avi", width, height)
cv2.destroyAllWindows()
myexample.release()
Running on a windows machine, Python 2.7.12, cv2 3.3.0
UPDATE
Eventually created the video using FFmpeg.
When you are running the for-loop, you are creating VideoWriters for every frame with same filename. Therefore it is over-writing the file with the new frame.
So, you have to create the VideoWriter object before entering the for-loop.
But doing that will not make your code working. There are some other errors due to misuse of commands.
First, os.listdir(path) will return list of filenames but not filepaths. Therefore you will need to add the folder path to that file name when you calling file read function (cv2.imread(imgPath+img)).
cv2.VideoWriter() will create the video file in the folder. Therefore it will also be listed in os.listdir(path). So you will need to remove files other than image files that you need. It can be done by checking the file extension.
After writing all the frames to the video, you will need to call the release() function to release the file handle.
And finally, makeVideo() function will not return anything. So there is no need to get it into a variable. (What you have to release() is file handler, but not the function as I said above).
Try the following code..
import cv2
import os
forexample = "C:/Users/me/Pictures/eg/"
eg = cv2.imread(forexample+'figure.jpg')
height , width , layers = eg.shape
print("ok, got that ", height, " ", width, " ", layers)
def makeVideo(imgPath, videodir, videoname, width, height):
video = cv2.VideoWriter(videodir+videoname,-1,1,(width, height))
for img in os.listdir(imgPath):
if not img.endswith('.jpg'):
continue
shot = cv2.imread(imgPath+img)
video.write(shot)
video.release()
print("one video done")
makeVideo(forexample,forexample, "example.avi", width, height)
cv2.destroyAllWindows()

I can't load an image in pygame/python2.7

Can someone help me load an image? It says "error: can't open tux.jpg:
import sys, pygame
pygame.init()
size = width, height = 600,400
screen = pygame.display.set_mode(size)
tux = pygame.image.load("tux.jpg")
screen.blit(tux,(200,200)) #Displays Tux On Screen
pygame.display.flip()
while 1:
for event in pygame.event.get():
if event.type == pygame.QUIT:sys.exit()
Please check that you have the image file within the directory that you are working in.
Using an absolute path may also be an option, for example:
tux = pygame.image.load("C:\\path\\to\\game\\tux.jpg")
For more information, please see this answer here.
The path you entered comes out as "./tux.png", i.e. the current working directory. Either place the file at the same location as your .py file (hence the default working directory for the script) or define the path to your image file.
For game file ordering, images are often in separate directories to the game scripts, The best way to do this is the os module. os.getcwd() gives the current working directory, and can be modified to the image directory using os.path.join. e.g.
game/
game.py
images/
tux.jgp
game.py uses pygame.load(os.path.join(os.getcwd(), "images")
(or define a datapath variable at the top in the same way if using lots of images!)

error when using pygame.image.load()

When I try to load an image in another folder I get...
pygame.error: Couldn't open sprites/testtile.png
I can load .png files just fine if they are in the same directory, but once they're in another folder I get this error.
I know that python has access to that other folder as well, because I get no error importing .py files from the folded.
When I try pygame.image.get_extended it returns a 0, but loading .png files from the same directory gives me no problems, so I don't think that's what is causing this issue.
I am running PyCharm by the way, and things like this always seem to give me trouble with this IDE. I don't even think it's a pygame issue. No clue what to do at this point.
FOLDER STRUCTURE:
scripts/GraphicsDriver.py
sprites/testtile.png
the driver is trying to access the testile.png file
Is the sprites directory in the directory with GraphicsDriver.py? You can run into some issues with the PyGame image loader. It looks for files in the same directory as PyGame was initialized from. Use 'os.path.join' to point it to the absolute path to your file.
I usually write my own little image loader around it though since it offers a little more flexibility to the process. Something like this which will return the image and a rect:
def load_image(name, colorkey = None):
"""loads an image and converts it to pixels. raises an exception if image not found"""
fullname = os.path.join('data', name)
try:
image = pygame.image.load(fullname)
except pygame.error, message:
print 'Cannot load image:', name
raise SystemExit, message
image = image.convert()
# set the colorkey to be the color of the top left pixel
if colorkey is not None:
if colorkey is -1:
colorkey = image.get_at((0,0))
image.set_colorkey(colorkey, RLEACCEL)
return image, image.get_rect()
Hopefully this will help.

Categories

Resources