Last active
July 29, 2023 04:43
-
-
Save villares/3e00c5c4e3366b18ebadb9073e46c6d1 to your computer and use it in GitHub Desktop.
monkey patching a Py5Image to allow pickling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import pickle | |
import py5 | |
from py5 import Py5Image | |
old_new = Py5Image.__new__ | |
def new_new(self, *args): | |
if args: | |
return old_new(self, *args) | |
else: | |
return object.__new__(Py5Image) | |
def getstate(self): | |
self.load_np_pixels() | |
return self.np_pixels | |
def setstate(self, d): | |
img = py5.create_image_from_numpy(d) | |
#self._instace = img._instance | |
self.__dict__ = img.__dict__ | |
def setup(): | |
global img, unpickled_img | |
py5.size(800, 800) | |
Py5Image.__getstate__ = getstate | |
Py5Image.__setstate__ = setstate | |
Py5Image.__new__ = new_new | |
img_path = 'sample.png' # Sample from sketh 2023_07_22 | |
img = py5.load_image(img_path) | |
unpickled_img = None | |
def draw(): | |
if unpickled_img is not None: | |
py5.image(unpickled_img, 0, 0) | |
def key_pressed(): | |
if py5.key == 'd': | |
with open('a.pickle', 'wb') as f: | |
pickle.dump(img, f) | |
elif py5.key == 'l': | |
global unpickled_img | |
with open('a.pickle', 'rb') as f: | |
unpickled_img = pickle.load(f) | |
py5.run_sketch(block=False) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment