def execute(self, context): #bpy.ops.render.render() bpy.data.images['Render Result'].save_render("somefile.tga") gmic.run("somefile.tga display") return {'FINISHED'}
def test_fuzzy_1d_4d_random_gmic_matrices(size_1d, size_2d, size_3d, size_4d, pixel_value_min, pixel_value_max): gmic_image_list = [] gmic_command = "{},{},{},{} rand {},{}".format(size_1d, size_2d, size_3d, size_4d, pixel_value_min, pixel_value_max) gmic.run(gmic_command, gmic_image_list) gmic_image = gmic_image_list[-1] # Using the default astype dkind: float32 # Using default output formatter: interleave=False, permute='xyzc' numpy_image = gmic_image.to_numpy_helper() assert numpy_image.shape == (size_3d, size_2d, size_1d, size_4d) assert numpy_image.dtype == numpy.float32 # Ensure numpy pixel values fit in the random values range numpy_image_min_value = numpy.amin(numpy_image) numpy_image_max_value = numpy.amax(numpy_image) assert pixel_value_min <= numpy_image_min_value <= pixel_value_max assert pixel_value_min <= numpy_image_max_value <= pixel_value_max # Ensure per-pixel equality in both numpy and gmic matrices for x in range(size_1d): for y in range(size_2d): for z in range(size_3d): for c in range(size_4d): assert numpy_image[z, y, x, c] == gmic_image(x, y, z, c)
def test_gmic_image_pixel_access(): images = [] gmic.run("sp apples", images) image = images[0] assert image(0, 0, 0, 0) == image() assert image(s=3) == image(0, 0, 0, 3) assert image(0, 2, 0, 2) == image(y=2, z=2)
def make_map(filename_without_ext, addresses, gmic_effect="fx_freaky_bw 90,20,0,0,0,0", no_display=False, prefix="LETTER"): m = StaticMap(800, 600, 80) g = gmic.Gmic("update") locator = Nominatim(user_agent="BerlinWallBreaker Agent") print("geocoding..") for address in addresses: loc = locator.geocode(address) icon_flag = IconMarker((loc.longitude, loc.latitude), './samples/icon-flag.png', 12, 32) m.add_marker(icon_flag) print(loc) image = m.render() output_filename1 = prefix + filename_without_ext + "_original.png" output_filename2 = prefix + filename_without_ext + ".png" image.save(output_filename1) print(output_filename1) if not no_display: g.run(output_filename1 + " display") if "_fx_stylize" in gmic_effect: gmic.run(output_filename1 + " " + gmic_effect + " output[2] " + output_filename2 + (" display[2]" if not no_display else "")) else: gmic.run(output_filename1 + " " + gmic_effect + " output " + output_filename2 + (" display" if not no_display else "")) print(output_filename2) return output_filename1, output_filename2
def make_sample_format_file(extension): filename = "{}_format_io_test.{}".format(extension, extension) gmic.run("sp apples output {}".format(filename)) yield filename os.unlink(filename)
def execute(self, context): #bpy.ops.render.render() bpy.data.images['Render Result'].save_render("somefile.tga") gmic.run( "somefile.tga fx_engrave 0.5,50,0,8,40,0,0,0,10,1,0,0,0,1,0 display" ) return {'FINISHED'}
def test_basic_from_numpy_helper_to_numpy_helper(): duck = [] gmic.run("sp duck", duck) original_duck_gmic_image = duck[0] duck_numpy_image = original_duck_gmic_image.to_numpy_helper( squeeze_shape=True) duck_io_gmic_image = gmic.GmicImage.from_numpy_helper(duck_numpy_image) assert_gmic_images_are_identical(original_duck_gmic_image, duck_io_gmic_image)
def numpy_PIL_duck(): import PIL.Image import numpy im1_name = "image.bmp" # 1. Generate duck bitmap, save it to disk gmic.run("sp duck -output " + im1_name) # 2. Load disk duck through PIL/numpy, make it a GmicImage yield numpy.array(PIL.Image.open(im1_name)) os.unlink(im1_name)
def test_basic_to_numpy_helper_from_numpy_helper(): gmic.run("sp duck output duck.png") import PIL.Image pil_image = numpy.array(PIL.Image.open("duck.png")) pil_gmic_image = gmic.GmicImage.from_numpy_helper(pil_image) duck_io_numpy_image = pil_gmic_image.to_numpy_helper(squeeze_shape=True) assert numpy.array_equal(duck_io_numpy_image, pil_image) assert_non_empty_file_exists("duck.png").unlink()
def test_file_format_io(extension): output_img = "aa." + extension with make_sample_format_file(extension) as input_img: # output with 100% quality gmic.run("{} output {}".format(input_img, output_img)) images = [] difference = get_images_difference_percent(input_img, output_img) if extension == "jpg": assert difference < 0.32 else: assert difference == 0 os.unlink(output_img)
def test_toolkit_to_PIL_advanced(): # to_PIL fine-graining parameters testing l = [] gmic.run("sp leno sp apples", l) PIL_leno = l[0].to_PIL(mode="HSV") assert PIL_leno.mode == "HSV" assert PIL_leno.width == l[0]._width assert PIL_leno.height == l[0]._height with pytest.raises(ValueError, match=r".*Too many dimensions.*"): l[1].to_PIL(squeeze_shape=False) # non-erroring commands l[1].to_PIL(astype=float) l[1].to_PIL(astype=numpy.uint8)
def test_toolkit_to_PIL(): # Compares G'MIC and PIL PNG lossless output with both square and non-square images l = [] PIL_leno_filename = "PIL_leno.png" PIL_apples_filename = "PIL_apples.png" gmic.run("sp leno sp apples", l) PIL_leno, PIL_apples = l[0].to_PIL(), l[1].to_PIL() PIL_leno.save(PIL_leno_filename, compress_level=0) PIL_apples.save(PIL_apples_filename, compress_level=0) PIL_reloaded_imgs = [] gmic.run(PIL_leno_filename + " " + PIL_apples_filename, PIL_reloaded_imgs) assert_non_empty_file_exists(PIL_leno_filename).unlink() assert_non_empty_file_exists(PIL_apples_filename).unlink() assert_gmic_images_are_identical(l[0], PIL_reloaded_imgs[0]) assert_gmic_images_are_identical(l[1], PIL_reloaded_imgs[1])
def test_gmic_user_file_autoload_and_use(gmic_instance_run, request, capfd): # Testing gmic user file auto-load for any type of G'MIC run technique # 1. Hack the file to auto-load, injecting a custom command into it gmic.run("echo_stdout $_path_user") gmic_home_user_file = capfd.readouterr().out.strip() assert gmic_home_user_file is not "" with gmic_any_user_file(gmic_home_user_file) as gmicpy_testing_command: # If gmic_instance_run is the current fixture (ie. run() method of a same instance singleton) # reinitialize it, it was created too early in the suite and is not fresh with autoloaded conf if inspect.isbuiltin( gmic_instance_run) and gmic_instance_run is not gmic.run: g = gmic.Gmic() gmic_instance_run = g.run # 2. Check that our custom command was auto-loaded as expected gmic_instance_run("sp leno " + gmicpy_testing_command)
def get_input_image_with_filter(path="../../img/resnet/swan-3299528_1280.jpg"): transform = transforms.Compose([ transforms.Resize(256), transforms.CenterCrop(224), transforms.ToTensor() ]) transform_normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406], std=[0.229, 0.224, 0.225]) img = Image.open(path) images = [] gmic.run(f'"{path}" normalize_local 8,10', images) img = images[0].to_PIL() transformed_img = transform(img) input = transform_normalize(transformed_img) input = input.unsqueeze(0) return input, transformed_img
def test_gmic_module_run_vs_single_instance_run_benchmark(): from time import time testing_command = "sp lena blur 10 blur 30 blur 4" testing_iterations_max = 100 expected_speed_improvement_by_single_instance_runs = 1.1 # at least 10% time_before_module_runs = time() for a in range(testing_iterations_max): gmic.run(testing_command) time_after_module_runs = time() time_before_instance_runs = time() gmic_instance = gmic.Gmic() for a in range(testing_iterations_max): gmic_instance.run(testing_command) time_after_instance_runs = time() assert (time_after_instance_runs - time_before_instance_runs ) * expected_speed_improvement_by_single_instance_runs < ( time_after_module_runs - time_before_module_runs)
def __getitem__(self, idx): """ :param idx: int :return: Tuple(array(3,244,244), int) """ if torch.is_tensor(idx): idx = idx.tolist() row = self.data.iloc[idx] img = Image.open(row["image"]).convert("RGB") if self.add_filters: if row["filter"] != "none": images = [] gmic.run(f'"{row["image"]}" {row["filter"]}', images) img = images[0].to_PIL() if self.rotate: img = img.rotate(int(row["rotation"])) if self.transformer: img = self.transformer(img) return img, int(row["class"])
def test_toolkit_from_PIL(): # Compares G'MIC and PIL PNG lossless output with both square and non-square images import PIL.Image l = [] gmic.run("sp leno sp apples", l) PIL_apples_filename = "PIL_apples.png" PIL_leno_filename = "PIL_leno.png" gmic.run("sp leno output " + PIL_leno_filename) PIL_leno = PIL.Image.open(PIL_leno_filename) leno = gmic.GmicImage.from_PIL(PIL_leno) assert_gmic_images_are_identical(l[0], leno) assert_non_empty_file_exists(PIL_leno_filename).unlink() gmic.run("sp apples output " + PIL_apples_filename) PIL_apples = PIL.Image.open(PIL_apples_filename) apples = gmic.GmicImage.from_PIL(PIL_apples) assert_gmic_images_are_identical(l[1], apples) assert_non_empty_file_exists(PIL_apples_filename).unlink()
def test_filling_empty_gmicimage_list_with_input_image_nonregtest_issue_30(): images = [] gmic.run(images=images, command="sp lena") assert len(images) == 1 assert type(images[0]) == gmic.GmicImage
import gmic from sys import argv command = "sp {} output {}.png".format(argv[1], argv[1]) print(command) input("?") gmic.run(command)
import gmic import PIL import PIL.Image import numpy from numpy import asarray, array_equal from matplotlib import pyplot l = [] gmic.run("sp duck", l) gmic.run("display", l) ll = l[0].to_numpy_helper(interleave=True, astype=numpy.uint8, squeeze_shape=True) print(ll.shape) print(ll.dtype) pyplot.imshow(ll) pyplot.show()
# See accompanying tutorial: https://discuss.pixls.us/t/developing-and-fiddling-with-the-gmic-python-binding/20406/3 import gmic import random import requests output_filename = "myframe.png" max_images = 70 filenames = [] for a in range(max_images): url = "https://picsum.photos/{}/{}".format(random.randint(50, 200), random.randint(50, 200)) filename = "picsum{}.png".format(a) filenames.append(filename) myfile = requests.get(url, allow_redirects=True) with open(filename, "wb") as f: f.write(myfile.content) gmic_command = "{} frame 3,3,0 frame 3,3,255 montage A display output {}".format( " ".join(filenames), output_filename) gmic.run(gmic_command)
import gmic carlo_filename = "carlo-acutis-isolated-face-for-warhol.jpg" carlo_gmic_images = [] gmic.run("{} resize2dx 1000 display".format(carlo_filename), carlo_gmic_images) carlo_w, carlo_h = carlo_gmic_images[0]._width, carlo_gmic_images[0]._height warhol_cmd = "warhol 5,5,0.47,37.92 display output carlo-warhol.png" gmic.run(warhol_cmd, carlo_gmic_images)
gmic.run(output_filename1 + " " + gmic_effect + " output " + output_filename2 + (" display" if not no_display else "")) print(output_filename2) return output_filename1, output_filename2 effectA = "_fx_stylize landscapenearantwerp +fx_stylize 1,6,0,0,2.17,3.65,3,0.5,0.1,3,3,0,0.7,1,0,1,0,5,5,7,1,30,10,2,1.85,0" effectB = "_fx_stylize redwaistcoat +fx_stylize 1,4,0,0,0.67,3.17,3,0.5,0.06,3,3,0,0.7,5,0,2,0,5,5,7,1,30,0,2.05,1.85,0" effectC = "_fx_stylize starrynight +fx_stylize 1,6,0,0,0.5,2,3,0.5,0.1,3,3,0,0.7,1,0,1,0,5,5,7,1,30,10,2,1.85,0" effectD = "fx_engrave 0.5,50,0,8,40,0,0,0,10,1,0,0,0,1,0" effectE = "fx_freaky_bw 90,20,0,0,0,0" levels = [] levels.append([ 'praha', [ 'karlovo namesti praha', 'vladislavova 11 praha', 'pivovar narodni praha', 'letna park praha', 'microsoft praha', 'waldstein garden, prague' ], effectE ]) # levels.append(['level2', ['Praha, Cesko', 'Riviere du Loup, Quebec, Canada'], effectE]) # levels.append(['level3', ['Caen, France', 'Le Havre, France'], effectE]) result_filenames = "" for a in levels: a.append(True) # toggle no_display parameter result_filenames += " ".join(make_map(*a)) + " " gmic.run(result_filenames + "display")
# See accompanying tutorial https://discuss.pixls.us/t/developing-and-fiddling-with-the-gmic-python-binding/20406/2 import gmic gmic.run('200,200,1,3 text "HELLO WORLD",50%,50%,13,1,255,147,23 display') # Use the 'output' command for outputting to a file gmic.run('200,200,1,3 text "HELLO WORLD",50%,50%,13,1,255,147,23 output helloworld.png')
# You should run first: pip install gmic # Make sure to checkout the README.md in this script's directory import gmic # The G'MIC module - for debugging mostly print(dir(gmic)) print(gmic.__spec__) print(gmic.__version__) print(gmic.__build__) help(gmic) # The G'MIC interpreter gmic.run("sp apples rodilius 3 display") gmic.run("sp earth blur 5 display") g1 = gmic.Gmic() g1.run("sp apples rodilius 3 display") del g1 g2 = gmic.Gmic() g2.run("sp earth blur 5 display") del g2 g = gmic.Gmic() g.run("sp apples rodilius 3") g.run("sp apples blur 5") # The G'MIC image im = gmic.GmicImage()
def test_gmic_image_to_numpy_helper_fuzzying(dtype1, dtype2, interleave1, interleave2, squeeze, gmic_command): expected_interleave_check = gmic_image_to_numpy_helper_default_interleave_param( interleave1) == gmic_image_to_numpy_helper_default_interleave_param( interleave2) params1 = {} params2 = {} if dtype1 is not None: params1["astype"] = dtype1 if dtype2 is not None: params2["astype"] = dtype2 if interleave1 is not None: params1["interleave"] = interleave1 if interleave2 is not None: params2["interleave"] = interleave2 params1["squeeze_shape"] = params2["squeeze_shape"] = squeeze single_image_list = [] gmic.run(images=single_image_list, command=gmic_command) gmic_image = single_image_list[0] # Test default dtype parameter is numpy.float32 numpy_image1 = gmic_image.to_numpy_helper(**params1) numpy_image2 = gmic_image.to_numpy_helper(**params2) assert numpy_image1.shape == numpy_image2.shape if gmic_image._depth > 1: # 3d image shape checking assert numpy_image1.shape == ( gmic_image._depth, gmic_image._height, gmic_image._width, gmic_image._spectrum, ) else: # 2d image shape checking if squeeze: assert numpy_image1.shape == ( gmic_image._height, gmic_image._width, gmic_image._spectrum, ) else: assert numpy_image1.shape == ( gmic_image._depth, gmic_image._height, gmic_image._width, gmic_image._spectrum, ) if dtype1 is None: dtype1 = numpy.float32 if dtype2 is None: dtype2 = numpy.float32 assert numpy_image1.dtype == dtype1 assert numpy_image2.dtype == dtype2 # Ensure arrays are equal only if we have same types and interlacing # Actually, they could be equal with distinct types but same interlacing, but are skipping cross-types compatibility analysis.. if (numpy_image1.dtype == numpy_image2.dtype) and expected_interleave_check: assert numpy.array_equal(numpy_image1, numpy_image2) del gmic_image del single_image_list del numpy_image1 del numpy_image2
# You should run first: pip install gmic # Make sure to checkout the README.md in this script's directory import gmic # THE HELP COMMAND(S) gmic.run("help blur") help(gmic) help(gmic.run) # THE SAMPLE OR SP COMMAND gmic.run("help sample") gmic.run("sample apples") # THE DISPLAY COMMAND gmic.run("sample apples display") gmic.run("sample duck sample apples display[0]") # THE PRINT COMMAND gmic.run("sp leno print") # THE OUTPUT <SOMEFILE> COMMAND gmic.run("sample earth output myearth.png") gmic.run("sample earth elephant output mysamples.jpeg") gmic.run("sample earth elephant output[1] myelephant.jpeg") # THE INPUT <SOMEFILE> COMMAND (simple and short form) gmic.run("input myearth.png display") gmic.run("myearth.png display")
# TEST 1: numpy(interleaved)->pyplot_display(interleaved)->gmic_from_nparray(deinterleaved)->gmic_display(deinterleaved) import gmic print(gmic.__spec__) import PIL import PIL.Image import numpy from numpy import asarray, array_equal from matplotlib import pyplot gmic.run("sp duck output image.png") i = PIL.Image.open("image.png") # Duck sample ii = asarray(i) print(ii.shape) # (512, 512, 3) print(ii.dtype) # uint8 l = [] gmic.run("sp duck", l) ll = l[0].to_numpy_helper(interleave=True, astype=numpy.uint8, squeeze_shape=True) array_equal(ll, ii) # True print(ll.shape) # (512, 512, 3) print(ll.dtype) # uint8 pyplot.imshow(ll) pyplot.show() # Good colors, dimensions and orientation pyplot.imshow(ii) pyplot.show() # Good colors, dimensions and orientation
# TEST 2: numpy(deinterleaved)->gmic_from_nparray(deinterleaved)->gmic_display(deinterleaved) import gmic import PIL import PIL.Image from numpy import asarray, array_equal gmic.run("sp duck output image.png") i = PIL.Image.open("image.png") ii = asarray(i) print(ii.shape) # (512, 512, 3) print(ii.dtype) # uint8 l = [] gmic.run("sp duck", l) ll = l[0].to_numpy_helper( interleave=False, astype=int, squeeze_shape=True) # default astype=float32, default squeeze_shape=True print(ll.shape) # (512, 512, 3) print(ll.dtype) # int64 array_equal( ll, ii) # False; uint8 vs. int64 match but deinterleave vs interleave unmatch j = gmic.GmicImage.from_numpy_helper(ll, deinterleave=False) gmic.run("display", j) # Good orientation, color, size """ [gmic]-1./ Display image [0] = '[unnamed]', from point (256,256,0). [0] = '[unnamed]': size = (512,512,1,3) [3072 Kio of floats]. data = (225,225,223,223,225,225,225,223,225,223,223,223,(...),78,78,78,77,91,80,79,89,77,79,79,82). min = 8, max = 251, mean = 128.241, std = 58.9512, coords_min = (457,60,0,1), coords_max = (425,20,0,0).
import gmic gmic.run( """ camera w ${"fitscreen {[w,h]}"},0,"G'MIC Webcam Demo" for {*}" && "!{*,ESC} rm camera +b 0.5% lightrays. , n. 0,255 blend add,0.9 w. wait 30 done camera 0,0 """ )