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.
Related
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)
I'm not able to add in images to my programme in Pycharm, I've imported Pygame and os and it wouldn't work. The image is in .png format 64 bit from flaticon.com
Is there something else I need to do to be able to add it in, I was following a PyGame tutorial online since I'm a beginner in programming
The python launcher just glitches when I add anything to do with an image. everything else works perfectly fine.
Here is the entire code of the project so far:
import pygame
import os
pygame.init()
screen = pygame.display.set_mode((800, 600))
pygame.display.set_caption("Space Invaders - GAME ONE (PyGame)")
playerImg = pygame.image.load('space-invaders.png')
playerX = 370
playerY = 480
running = True
while running:
for event in pygame.event.get():
if event.type == pygame.QUIT:
running = False
screen.fill((0, 0, 0))
pygame.display.update()
this is the error message:
playerImg = pygame.image.load('space-invaders.png')
pygame.error: Couldn't open space-invaders.png
Process finished with exit code 1
it just glitches with any addition of an image. If I remove all image related code, it works fine
Also, import os just greys out in the editor
First check if the image is in the same folder as your .py. Next, make sure the image is really .png not just renamed for example, check this by trying to load another image. Last but not the least, check the spelling, maybe the name of the picture is misspelled. Since you are not using paths I can't remember anything else that could cause the issue.
Also, I do not know if it is the mistake during the copy process but last 2 lines of code need to be inside the for loop. And why you have imported os?
EDIT: Answer to the OP question in the comment
By importing os you can now use this module, nothing more. Here is how you can locate your .png file:
current_dir = os.path.dirname(__file__) #The location of your `.py`
img_dir = os.path.join(current_dir, "img_dir") #Path to the folder where your `png` is
player_img = pygame.image.load(os.path.join(img_dir, "space-invaders.png"))
Instead of "img_dir" you need to put the name of your folder, or the path, depending on the folder location.
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.
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()
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!)