Python - couldn't open image - pygame

IMAGE WITH ERROR IN MY PYTHON GAME:
I want to run my application, but see this error, how to fix it?
Image with a correctly format is not a possible to open, this is a simple game make in a Python
import random
from livewires import games
games.init(screen_width=640,screen_height=480,fps=50)
class Ship(games.Sprite):
def update(self):
if games.keyboard.is_pressed(games.K_RIGHT):
self.angle+=1
if games.keyboard.is_pressed(games.K_LEFT):
self.angle-=1
if games.keyboard.is_pressed(games.K_1):
self.angle=0
if games.keyboard.is_pressed(games.K_2):
self.angle=90
if games.keyboard.is_pressed(games.K_3):
self.angle=180
if games.keyboard.is_pressed(games.K_4):
self.angle=270
class Asteroid(games.Sprite):
SMALL = 1
MEDIUM = 2
LARGE = 3
images={SMALL : games.load_image("asteroida_s.bmp"),
MEDIUM : games.load_image('asteroida_m.bmp'),
LARGE : games.load_image('asteroida_l.bmp') }
SPEED=2
def main():
nebula_image=games.load_image("mglawica.jpg")
games.screen.background=nebula_image
for i in range(8):
x=random.randrange(games.screen.width)
y=random.randrange(games.screen.height)
size-random.choice([Asteroid.SMALL,Asteroid.MEDIUM,Asteroid.LARGE,])
new_asteroid=Asteroid(x=x,y=y,size=size)
game.screen.add(new_asteroid)
games.screen.mainloop()
def main():
nebula_image=games.load_image("mglawica.jpg",transparent=false)
games.screen.background=nebula_image
ship_image=games.load_image("statek.bmp")
the_ship=Ship(image=ship_image,
x=games.scren.width/2,
y=games.scren.height/2)
games.scren.add(the_ship)
games.screen.mainloop()
def play(self):
nebula_image=games.load_image("mglawica.jpg")
games.screen.background=nebula_image
self.advance()
games.screen.mainloop()
def advanced(self):
self.level+=1
BUFFER=150
for i in range(self.level):
x_min=random.randrage(BUFFER)
y_min=BUFFER-x_min
x=self.ship.x+x_distance
y=self.ship.y+y_distance
x%=games.screen.width
y%=games.screen.height
new_asteroid=Asteroid(game=self,x=x,y=y,size=Asteroid.LARGE)
game.screen.add(new_asteroid)
def end():
end_message=games.Message(value="Koniec gry",
size=90,
color=color.red,
x=games.screen.width/2,
y=games.screen.height/2,
lifetime=10*games.scren.fps,after_death=games.screen.quit,
is_sollideable=False)
games.scren.add(end_message)
def die(self):
if self.size !=Asteroid.SMALL:
for i in range(Asteroid.SMALL):
new_asteroid=Asteroid(x=self.x,
y=self.y,
size=self.size-1)
game.screen.add(new_asteroid)
self.destroy()

While your code is very messy (no indentation), I think I have a way to fix it. First, I question your need to import livewire, and also wonder why you marked this question as pygame. You never imported pygame. So my solution will be written in pygame.
First, you have to load the images (and if you want assign it to a variable):
image = pygame.image.load(filename)
Then, you have to convert the Surface, or basically just the image.
image = pygame.image.load(filename).convert()

Related

In Gtk, how to make a window smaller when creating

I am trying to display both an image and a box with an Entry widget. I can do that, but the window is so large that the widget at the bottom is mostly out of view. I have tried several calls to set the window's size or unmaximize it, but they seem to have no effect. I determined that the problem only occurs when the image is large, but still wonder how to display a large image in a resizable window or, for that matter, to make any changes to the window's geometry from code. All the function call I tried seem to have no effect.
Here is my code:
import gi
gi.require_version("Gtk", "3.0")
from gi.repository import Gtk
from gi.repository import GdkPixbuf
from urllib.request import urlopen
class Display(object):
def __init__(self):
self.window = Gtk.Window()
self.window.connect('destroy', self.destroy)
self.window.set_border_width(10)
# a box underneath would be added every time you do
# vbox.pack_start(new_widget)
vbox = Gtk.VBox()
self.image = Gtk.Image()
response = urlopen('http://1.bp.blogspot.com/-e-rzcjuCpk8/T3H-mSry7PI/AAAAAAAAOrc/Z3XrqSQNrSA/s1600/rubberDuck.jpg').read()
pbuf = GdkPixbuf.PixbufLoader()
pbuf.write(response)
pbuf.close()
self.image.set_from_pixbuf(pbuf.get_pixbuf())
self.window.add(vbox)
vbox.pack_start(self.image, False, False, 0)
self.entry = Gtk.Entry()
vbox.pack_start(self.entry, True,True, 0)
self.image.show()
self.window.show_all()
def main(self):
Gtk.main()
def destroy(self, widget, data=None):
Gtk.main_quit()
a=Display()
a.main()
Most of the posted information seems to pertain to Gtk2 rather than Gtk3, but there is a solution: to use a pix buf loader and set the size:
from gi.repository import Gtk, Gdk, GdkPixbuf
#more stuff
path = config['DEFAULT']['datasets']+'working.png'
with open(path,'rb') as f:
pixels = f.read()
loader = GdkPixbuf.PixbufLoader()
loader.set_size(400,400)
loader.write(pixels)
pb = GdkPixbuf.Pixbuf.new_from_file(path)
self.main_image.set_from_pixbuf(loader.get_pixbuf())
loader.close()

How do I load multiple grayscale images as a single tensor in pytorch?

I'm currently trying to use a stack a set of images as a single entity for each label to train a CNN on using cross-validation. Given a dataset of 224x224x1 grayscale images sorted by:
Root/
Class0/image0_view0.png
Class0/image0_view1.png
Class0/image0_view2.png
...
Class1/image0_view0.png
Class1/image0_view1.png
Class1/image0_view2.png
How would I go about flowing 3 images (view 0, 1, and 2) as a single tensor with dimensions 224x224x3 (3 grayscale images)? In other words, how would I create a dataset of image stacks in pytorch using ImageFolder/DatasetFolder and DataLoader? Would I have to re-organize my folders and classes, or would it be easier to make the stacks when I make the splits for cross-validation?
Thank you for your time and help! Let me know if I can provide any more info.
I had a very similar task. I needed to load a random sequence of 3 images as an element of a batch for training the network not on separate images but on seq of images. For batch size 8, I have 8 x 3 = 24 images. This seems to be very similar to different views in your case. I used imread_collection functionality from skimage.io. I added such a getitem to the Dataset class:
def __getitem__(self, idx):
idx_q = int(torch.randint(0 + self.boundary, self.length - self.boundary, (1,)))
q = imread_collection([self.image_paths[idx_q-1], self.image_paths[idx_q], self.image_paths[idx_q+1]], conserve_memory=True)
if self.transform:
q = torch.stack([self.transform(img) for img in q])
return q, p, n
Here I generate a random index of an image and then load three consecutive images using imread_collection and self.image_paths, which is the list with paths to all images. Then I do transform of each image and stack them. In your case, you should think about using the right indexes, maybe by applying a sliding window on the length of self.image_paths.
A bit more info could be found on the torch forum. I also tried to ask and find a more elegant solution, but couldn't and successfully trained the model with such an approach.
How do I load multiple grayscale images as a single tensor in pytorch?
In general, the number of channels is not important.
The operation known as "loading a batch of data" is what you need. For this PyTorch has DataLoader class. DataLoader class further needs Dataset class.
If in DataLoader the batch size is 64 (bs=64) you will load 64 images from once as tensor.
If you use ImageFolder this will not return minibatch for you. ImageFolder is a Dataset derived class.
The problem with ImageFolder (if you just use that) is you will get a single image per index. You would combine multiple images to a minibatch then.
Here is one example using ImageFolder with CIFAR10 data.
from torchvision import transforms
imagef = torchvision.datasets.ImageFolder(r'C:\Users\dj\data\cifar10\test', transform=transforms.ToTensor())
print(imagef)
print(imagef.classes)
img, label = imagef[0]
display(img)
print(img.size())
print(label)
Out:
Dataset ImageFolder
Number of datapoints: 10000
Root location: C:\Users\dj\data\cifar10\test
StandardTransform
Transform: ToTensor()
['airplane', 'automobile', 'bird', 'cat', 'deer', 'dog', 'frog', 'horse', 'ship', 'truck']
tensor([[[0.6078, 0.6549, 0.6902, ..., 0.7882, 0.7922, 0.7529],
[0.6000, 0.6392, 0.6706, ..., 0.7922, 0.7961, 0.7412],
[0.6078, 0.6275, 0.6588, ..., 0.8078, 0.8000, 0.7412],
...,
[0.3490, 0.2235, 0.2392, ..., 0.3490, 0.2314, 0.2627],
[0.3490, 0.2353, 0.2471, ..., 0.2235, 0.2392, 0.2941],
[0.3608, 0.2353, 0.2392, ..., 0.2353, 0.2510, 0.2863]], ...
torch.Size([3, 32, 32])
0
The next example is based on DataLoader:
import torch
from torch.utils.data import DataLoader, Dataset
import torchvision
from torchvision import transforms
import PIL.Image as Image
def pil_loader(path):
with open(path, 'rb') as f:
img = Image.open(f)
return img.convert('RGB')
ds = torchvision.datasets.DatasetFolder(r'C:\Users\dj\data\cifar10\test',
loader=pil_loader,
extensions=('.png'),
transform=transforms.ToTensor())
dl = DataLoader(ds, batch_size=2)
len(dl)
for imgs,lbls in dl:
print(imgs.size()) # torch.Size([2, 3, 32, 32])
break
This DataLoader is what you may need. The one I present, has the custom loading function: pil_loader.
You can also use ImageFolder instead of DatasetFolder in the previous example.
That would be something like:
ds = torchvision.datasets.ImageFolder(r'C:\Users\dj\data\cifar10\test', transform=transforms.ToTensor())
dl = DataLoader(ds, batch_size=3)
print(len(dl))
for imgs,lbls in dl:
print(imgs.size())
break

how do you use pygame.sprite.Sprite?

I am currently writing a small game under separate files and am having an issue with pygame.sprite.Sprite. Every time I go to run the player class I get this error AttrbuteError: "module" object has no attribute "sprite". I have done many searches on this site and have also looked on the pygame website for answers but I have only found other bits of code and answers that do not resolve my current issue. If anyone could help me with my issue that would be great.
here's my class for the player:
import pygame
import pygame.sprite as Sprite
class player(Sprite.sprite):
def _init_(self,plyrmovement,plyrhealth,plyrdirection):
Sprite.Sprite._init_(self)
def plyrmovement(left,right):
position=[100,100]
direct_left = 'player left'
direct_right = 'player right'
def right():
if event.key == ord('d'):
position[0] += 5
plyrdirection = direct_right
sprite.sprite='playerleft'
def left():
if event.key == ord('a'):
position[0] -= 5
plyrdirection = direct_left
sprite.sprite = 'playerright'
def shoot(self,bullet):
if event.key == K_SPACE:
bullet.bulletmove
def plyrhealth(self):
self.health = 100
class bullet(pygame.Sprite.Sprite):
def _init_(self,bulletmove,bulletdamage):
pygame.image.load('bullet sprite.png')
The full name is pygame.sprite.Sprite.
If you use import pygame.sprite as Sprite then correct name is player(Sprite.Sprite) not player(Sprite.sprite) - see upper S in both Sprite.
As for me it is better to use class player(pygame.sprite.Sprite) and bullet(pygame.sprite.Sprite) - lower s in first sprite and upper S in second Sprite - and without import pygame.sprite as Sprite
import pygame
class Player(pygame.sprite.Sprite):
def __init__(self,plyrmovement, plyrhealth, plyrdirection):
pygame.sprite.Sprite.__init__(self)
# ...rest...
class Bullet(pygame.sprite.Sprite):
def __init__(self, bulletmove, bulletdamage):
pygame.sprite.Sprite.__init__(self)
# ...rest...
BTW:
it has to be two _ before and after init
you could use CamelCase names for classes - Player, Bullet - similar to Sprite, Rect. See suggestions in PEP8 (PEP 0008 -- Style Guide for Python Code)(PEP8 - Class Names)
use empty line before class and def to make code more readable (PEP8 - Blank Lines).

How do I rerender HTML PyQt4

I have managed to use suggested code in order to render HTML from a webpage and then parse, find and use the text as wanted. I'm using PyQt4. However, the webpage I am interested in is updated frequently and I want to rerender the page and check the updated HTML for new info.
I thus have a loop in my pythonscript so that I sort of start all over again. However, this makes the program crash. I have searched the net and found out that this is to be expected, but I have not found any suggestion on how to do it correctly. It must be simple, I guess?
from PyQt4.QtGui import *
from PyQt4.QtCore import *
from PyQt4.QtWebKit import *
class Render (QWebPage):
def __init__(self, url):
self.app = QApplication(sys.argv)
QWebPage.__init__(self)
self.loadFinished.connect(self._loadFinished)
self.mainFrame().load(QUrl(url))
self.app.exec_()
def _loadFinished(self, result):
self.frame = self.mainFrame()
self.app.quit()
r = Render(url)
html = r.frame.toHtml()
S,o when I hit r=Render(url) the second time, it crashes. S,o I am looking for something like r = Rerender(url).
As you might guess, I am not much of a programmer, and I usually get by by stealing code I barely understand. But this is the first time I can't find an answer, so I thought I should ask a question myself.
I hope my question is clear enough and that someone has the answer.
Simple demo (adapt to taste):
import sys, signal
from PyQt4 import QtCore, QtGui, QtWebKit
class WebPage(QtWebKit.QWebPage):
def __init__(self, url):
super(WebPage, self).__init__()
self.url = url
self.mainFrame().loadFinished.connect(self.handleLoadFinished)
self.refresh()
def refresh(self):
self.mainFrame().load(QtCore.QUrl(self.url))
def handleLoadFinished(self):
print('Loaded:', self.mainFrame().url().toString())
# do stuff with html ...
print('Reloading in 3 seconds...\n')
QtCore.QTimer.singleShot(2000, self.refresh)
if __name__ == '__main__':
signal.signal(signal.SIGINT, signal.SIG_DFL)
app = QtGui.QApplication(sys.argv)
webpage = WebPage('http://en.wikipedia.org/')
print('Press Ctrl+C to quit\n')
sys.exit(app.exec_())

Write custom widget with GTK3

I am trying to find the simplest example of a custom widget being written for Gtk-3.
So far the best thing I've found is this (using PyGTK), but it seems to be targeted to Gtk-2.
BTW: I don't care the language it is written in, but if we can avoid C++, much better!
Python3 Gtk3 it is, then:
from gi.repository import Gtk
class SuperSimpleWidget(Gtk.Label):
__gtype_name__ = 'SuperSimpleWidget'
Here is a non-trivial example that actually does something, namely paints its background and draws a diagonal line through it. I'm inheriting from Gtk.Misc instead of Gtk.Widget to save some boilerplate (see below):
class SimpleWidget(Gtk.Misc):
__gtype_name__ = 'SimpleWidget'
def __init__(self, *args, **kwds):
super().__init__(*args, **kwds)
self.set_size_request(40, 40)
def do_draw(self, cr):
# paint background
bg_color = self.get_style_context().get_background_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*list(bg_color))
cr.paint()
# draw a diagonal line
allocation = self.get_allocation()
fg_color = self.get_style_context().get_color(Gtk.StateFlags.NORMAL)
cr.set_source_rgba(*list(fg_color));
cr.set_line_width(2)
cr.move_to(0, 0) # top left of the widget
cr.line_to(allocation.width, allocation.height)
cr.stroke()
Finally, if you really want to derive from Gtk.Widget then you also have to set up a drawing background. Gtk.Misc does that for you, but Gtk.Widget could be a container that doesn't actually draw anything itself. But inquiring minds want to know, so you could do it like so:
from gi.repository import Gdk
class ManualWidget(Gtk.Widget):
__gtype_name__ = 'ManualWidget'
def __init__(self, *args, **kwds):
# same as above
def do_draw(self, cr):
# same as above
def do_realize(self):
allocation = self.get_allocation()
attr = Gdk.WindowAttr()
attr.window_type = Gdk.WindowType.CHILD
attr.x = allocation.x
attr.y = allocation.y
attr.width = allocation.width
attr.height = allocation.height
attr.visual = self.get_visual()
attr.event_mask = self.get_events() | Gdk.EventMask.EXPOSURE_MASK
WAT = Gdk.WindowAttributesType
mask = WAT.X | WAT.Y | WAT.VISUAL
window = Gdk.Window(self.get_parent_window(), attr, mask);
self.set_window(window)
self.register_window(window)
self.set_realized(True)
window.set_background_pattern(None)
Edit and to actually use it:
w = Gtk.Window()
w.add(SimpleWidget())
w.show_all()
w.present()
import signal # enable Ctrl-C since there is no menu to quit
signal.signal(signal.SIGINT, signal.SIG_DFL)
Gtk.main()
Or, more fun, use it directly from the ipython3 REPL:
from IPython.lib.inputhook import enable_gtk3
enable_gtk3()
w = Gtk.Window()
w.add(SimpleWidget())
w.show_all()
w.present()
Here's a tutorial about writing a GTK 3 custom container widget in C: http://ptomato.name/advanced-gtk-techniques/html/custom-container.html It's probably more complicated than you need for writing a simple widget. You might also check out the migration guide from GTK 2 to 3: https://developer.gnome.org/gtk3/stable/gtk-migrating-2-to-3.html
SO far the best reference to:
- understand Gobject (from wich gtk widget derive)
- have some boiler code and c code
https://developer.gnome.org/gobject/stable/howto-gobject.html
I know it's not Python written, but converting from c to python is a piece of cake
(what matter is the algorithm, not the language)