Esempio n. 1
0
def python_runway(img, layer):
    if not layer.is_rgb:
        raise ValueError("Expected RGB layer")
    # because pdb cannot save to a buffer, we have to use a temporary file instead
    f = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
    f.close()
    pdb.file_png_save(img, layer, f.name, f.name, 0, 9, 0, 0, 0, 0, 0)
    # convert data from file to base64 encoded bytes
    data = open(f.name, "rb").read()
    b64 = base64.b64encode(data)
    os.unlink(f.name)
    # send data to Runway via a POST request
    data = json.dumps({"semantic_map": b64})
    req = urllib2.Request("http://localhost:8000/query", data,
                          {"Content-Type": "application/json"})
    f = urllib2.urlopen(req)
    resp = json.loads(f.read())
    f.close()
    # save result to a temporary file, because pdb cannot load from a buffer
    jpg = base64.b64decode(resp["output"][22:])
    f = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
    f.close()
    open(f.name, "wb").write(jpg)
    # open the temp file
    image = pdb.gimp_file_load(f.name, f.name)
    # copy the first layer to clipboard
    pdb.gimp_edit_copy(image.layers[0])
    os.unlink(f.name)
    # paste clipboard contents as a floating selection
    floating = pdb.gimp_edit_paste(layer, 0)
    floating.name = layer.name + " [Runway]"
Esempio n. 2
0
def run(directory, rewrite = False):
	from gimpfu import pdb
	start = time.time()
	#for all xcf files in working directory
	print("Running on directory '{0}'".format(directory))
	for filename in os.listdir(directory):
		if filename[-4:] in allowedFormat:
			print("Found a file : '{0}'".format(filename))
			image = pdb.gimp_file_load(os.path.join(directory, filename), os.path.join(directory, filename))

			with open(os.path.join(directory, os.path.splitext(filename)[0]+".desc"), "wb") as f:
				for layer in image.layers:
					for c in [layer] + layer.children:
						f.write("texture = {}\n"\
								"size = {}, {}\n"\
								"position = {}, {}\n".format(c.name, c.width, c.height, *c.offsets))

						print("Write layer '{0}' in '{0}.png'".format(c.name))
						# write the new png file
						pdb.file_png_save(image, c, os.path.join(directory, c.name +".png"), 
													os.path.join(directory, c.name +".png"), 
													0, 9, 0, 0, 0, 0, 0)

	end = time.time()
	print("Finished, total processing time : {0:.{1}f}".format(end-start, 2))
def caches(inImg, inNameLayerFleche, inNameLayerFond):
    path_cadenas = GRAPH_PATH + "images/cadenas.png"
    imagecadenas = pdb.gimp_file_load(path_cadenas, path_cadenas)
    layercadenas = pdb.gimp_image_get_active_layer(imagecadenas)

    pdb.gimp_selection_all(imagecadenas)
    pdb.gimp_edit_copy(layercadenas)
    pdb.gimp_image_delete(imagecadenas)

    layerfond = pdb.gimp_image_get_layer_by_name(inImg, inNameLayerFond)
    layerfleche = pdb.gimp_image_get_layer_by_name(inImg, inNameLayerFleche)
    _, alayers = pdb.gimp_image_get_layers(inImg)

    for layercurrent in alayers:
        pdb.gimp_selection_none(inImg)
        layercurrent = gimp.Item.from_id(layercurrent)
        pdb.script_fu_add_bevel(inImg, layercurrent, 5, 0, 0)

        pdb.gimp_item_set_visible(layercurrent, False)
        layername = pdb.gimp_item_get_name(layercurrent)
        if not (layername == inNameLayerFleche
                or layername == inNameLayerFond):
            cree_background(layercurrent, layerfond, inImg)

    cache = pdb.gimp_image_merge_visible_layers(inImg, CLIP_TO_IMAGE)
    pdb.script_fu_add_bevel(inImg, cache, 5, 0, 0)
    pdb.gimp_item_set_name(cache, "cache.png")

    pdb.gimp_image_lower_item_to_bottom(inImg, layerfleche)
    pdb.gimp_image_lower_item_to_bottom(inImg, cache)
    pdb.gimp_image_lower_item_to_bottom(inImg, layerfond)
Esempio n. 4
0
def run(directory, rewrite=False):
    from gimpfu import pdb
    start = time.time()
    #for all xcf files in working directory
    print("Running on directory '{0}'".format(directory))
    for filename in os.listdir(directory):
        if filename[-4:] in allowedFormat:
            print("Found a file : '{0}'".format(filename))
            image = pdb.gimp_file_load(os.path.join(directory, filename),
                                       os.path.join(directory, filename))

            with open(
                    os.path.join(directory,
                                 os.path.splitext(filename)[0] + ".desc"),
                    "wb") as f:
                for layer in image.layers:
                    for c in [layer] + layer.children:
                        f.write("texture = {}\n"\
                          "size = {}, {}\n"\
                          "position = {}, {}\n".format(c.name, c.width, c.height, *c.offsets))

                        print("Write layer '{0}' in '{0}.png'".format(c.name))
                        # write the new png file
                        pdb.file_png_save(
                            image, c, os.path.join(directory, c.name + ".png"),
                            os.path.join(directory, c.name + ".png"), 0, 9, 0,
                            0, 0, 0, 0)

    end = time.time()
    print("Finished, total processing time : {0:.{1}f}".format(end - start, 2))
def cutter_batch_images(
        src_dir, src_ftype,
        limit, sl_thresh, sz_thresh,
        bg_manual, bg_color, bg_corner, bg_x, bg_y,
        padding, deskew, sq_crop,
        save_same, save_dir, save_ftype, save_dpi, jpg_qual, save_suffix
    ):
    ftype_match = {
        'jpg': '\.[jJ][pP][eE]?[gG]$',
        'bmp': '\.[bB][mM][pP]$',
        'png': '\.[pP][mnNM][gG]$',
        'tif': '\.[tT][iI][fF][fF]?$',
    }
    fn_match = re.compile(ftype_match.get(src_ftype, 'jpg'))
    for fn in os.listdir(src_dir):
        if not os.path.isfile(fn) or not fn_match.search(fn):
            continue
        pdb.gimp_progress_set_text('Processing %s...' % (fn, ))
        image = pdb.gimp_file_load(fn, fn)
        if not image:
            pdb.gimp_progress_set_text('Error loading %s...' % (fn, ))
            continue

        cutter_single_image(
            image, image.active_layer,
            limit, sl_thresh, sz_thresh,
            bg_manual, bg_color, bg_corner, bg_x, bg_y,
            padding, deskew, sq_crop, True,
            save_same, save_dir, save_ftype, save_dpi, jpg_qual, save_suffix
        )

        pdb.gimp_delete_image(image)

    pdb.gimp_progress_end()
def layer_images(imageFiles):
    """Joins imageFiles as layers."""
    initialFile = next(imageFiles)
    layeredImage = pdb.gimp_file_load(initialFile, initialFile)
    for imageFile in imageFiles:
        newLayer = pdb.gimp_file_load_layer(layeredImage, imageFile)
        pdb.gimp_image_insert_layer(layeredImage, newLayer, None, 0)
    return layeredImage 
Esempio n. 7
0
def _iterate_folder(input_folder, output_folder, func):
    """ Apply a given function to a folder of images.
    """
    for file_name in os.listdir(input_folder):
        if not (file_name.endswith('.png') or file_name.endswith('.jpg')):
            continue

        img = pdb.gimp_file_load(os.path.join(input_folder, file_name),
                                 file_name)
        drawable = img.layers[0]
        func(img, drawable, output_folder)
Esempio n. 8
0
def flip(file):
    fileabs = os.path.abspath(file)
    print(fileabs)
    file_dir, filename = os.path.split(fileabs)
    filename = filename.lower().replace('.png', '_mini.jpg')
    file_new = os.path.join(file_dir, filename)

    image = pdb.gimp_file_load(file, file)
    drawable = pdb.gimp_image_get_active_layer(image)

    #pdb.gimp_image_flip(image, ORIENTATION_HORIZONTAL)
    #pdb.gimp_file_save(image, drawable, file_new, file_new)

    pdb.file_jpeg_save(image, drawable, file_new, file_new, 0.8, 0, 1, 1, '', 0, 1, 0, 0)
    pdb.gimp_image_delete(image)
    def __getForegroundImageAndDrawable(self, filename_foreground):
        """
		Use GIMP to get the image and drawable objects from the forground image.


		Parameters:

		filename_forground (String) : The filename of the forground image file.


		Returns:

		NA


		Invoked by :

		OverlayImageAgent.runMultipleFromList


		Invokes :

		NA
		"""

        nameProcedure = "OverlayImageAgent::__getImageAndDrawable"

        print("%s : Enter" % (nameProcedure))

        # Get the following from both the foreground image file;
        #
        #   - image
        #   - drawable
        #
        # and save them into the appropriate global variables.

        self.image_foreground = pdb.gimp_file_load(filename_foreground,
                                                   filename_foreground)
        self.drawable_foreground = pdb.gimp_image_get_active_layer(
            self.image_foreground)

        print("Filename foreground image = %s" %
              self.image_foreground.filename)

        gimp.progress_init(
            "Have got image and drawable from Foreground Image file")

        print("%s : Exit" % (nameProcedure))
Esempio n. 10
0
def change_num(image, inNumero):
    layer = pdb.gimp_image_get_active_layer(image)

    pdb.gimp_context_set_sample_transparent(True)
    pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE,layer, 1, 1)
    pdb.gimp_selection_invert(image)
    _, x, y, x2, y2  = pdb.gimp_selection_bounds(image)
    xthird=x  + ((x2 - x) // 4  * 3)

    y = _find_black_not_transparent(image, layer, xthird, y)

    pdb.gimp_context_set_sample_transparent(False)
    pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE, layer, xthird, y)
    pdb.gimp_edit_clear(layer)
                    
    if inNumero > 1:        
        _, x, y, x2, y2  = pdb.gimp_selection_bounds(image)
        ymiddle = y + ( (y2 - y) // 2)

        keep = True
        while keep:
            if not _is_transparent(image, layer, x, ymiddle):
                keep = False
                pdb.gimp_context_set_sample_transparent(False)
                pdb.gimp_context_set_sample_threshold(1)
                pdb.gimp_image_select_contiguous_color(image, CHANNEL_OP_REPLACE, layer, x+1, ymiddle)
                pdb.gimp_context_set_sample_threshold(0.1)
 
            x += 1
        pdb.gimp_edit_clear(layer)

        _, x1, y1, x2, y2  = pdb.gimp_selection_bounds(image)
        
        pdb.gimp_image_select_rectangle(image, CHANNEL_OP_REPLACE, x1, y1, x2-x1, y2-y1)
        
        filename = GRAPH_PATH + str(inNumero) + ".png"

        imagechiffre = pdb.gimp_file_load(filename, filename)
        layerchiffre = pdb.gimp_image_get_active_layer(imagechiffre)
        
        pdb.gimp_selection_all(imagechiffre)
        pdb.gimp_edit_copy(layerchiffre)
        pdb.gimp_image_delete(imagechiffre)
        
        floating_sel = pdb.gimp_edit_paste(layer,False)
        pdb.gimp_floating_sel_anchor(floating_sel)
Esempio n. 11
0
def plugin_main(file):
    """
    Main plugin method
    """

    image = pdb.gimp_file_load(file, file)
    drawable = pdb.gimp_image_get_active_layer(image)

    fileabs = os.path.abspath(file)
    #gprint('=== Input ==== ' + fileabs)
    file_dir, filename = os.path.split(fileabs)
    filename = filename[:-4] + '.jpg'
    file_new = os.path.join(OUTPUT_PATH, filename)

    pdb.file_jpeg_save(image, drawable, file_new, file_new, QUALITY, 0, 1, 1, '', 0, 1, 0, 0)
    pdb.gimp_image_delete(image)

    gprint('=== Output === ' + file_new)
Esempio n. 12
0
def texte(inR,inG,inB,inFichier,highlight_text,change_numero):
    print("\tLoading image {}".format(inFichier))
    image = pdb.gimp_file_load(inFichier,inFichier)
    color = (inR,inG,inB)

    # pdb.gimp_display_new(image)
    if highlight_text:
        print("\t\tHighlighting text...")
        effet_texte(color, image)
    
    if change_numero > 0:
        print("\t\tChanging number...")
        change_num(image, change_numero)
    
    pdb.gimp_selection_none(image)
    layer_id = pdb.gimp_image_get_layers(image)[1][0]
    layer = gimp.Item.from_id(layer_id)
    pdb.script_fu_add_bevel(image, layer, 5, False, False)
    drawable = pdb.gimp_image_get_active_drawable(image)

    pdb.file_png_save(image, drawable, inFichier, inFichier,
                        0,5,0,0,0,0,0) 
    pdb.gimp_image_delete(image)
Esempio n. 13
0
def python_gaugan(img, layer, style="random"):
    if not layer.is_rgb:
        raise ValueError("Expected RGB layer")
    # because pdb cannot save to a buffer, we have to use a temporary file instead
    f = tempfile.NamedTemporaryFile(suffix=".png", delete=False)
    f.close()
    pdb.file_png_save(img, layer, f.name, f.name, 0, 9, 0, 0, 0, 0, 0)
    data = open(f.name, "rb").read()
    os.unlink(f.name)
    # send to GauGAN API
    gaugan = GauganAPI()
    jpg = gaugan.convert(data, style)
    # save result to a temporary file, because pdb cannot load from a buffer
    f = tempfile.NamedTemporaryFile(suffix=".jpg", delete=False)
    f.close()
    open(f.name, "wb").write(jpg)
    # open the temp file
    image = pdb.gimp_file_load(f.name, f.name)
    # copy the first layer to clipboard
    pdb.gimp_edit_copy(image.layers[0])
    os.unlink(f.name)
    # paste clipboard contents as a floating selection
    floating = pdb.gimp_edit_paste(layer, 0)
    floating.name = layer.name + " [GauGAN]"
def createTechIcons(timg, tdrawable,file,folder, outFolder,scaleTo):
  for fileName in os.listdir(folder):
    # backGroundImage=pdb.gimp_file_load(file, file)
    # backGroundLayer=backGroundImage.layers[0]
    if fileName[-4:]!=".dds":
      continue
    outFile=outFolder+"/"+"tech_"+fileName
    image=pdb.gimp_file_load(folder+"/"+fileName, folder+"/"+fileName)
    pdb.gimp_image_scale(image,scaleTo,scaleTo)
    pdb.gimp_image_resize(image,52,52,-1,-1)
    for layer in image.layers:
      pdb.gimp_layer_resize_to_image_size(layer)
    # layer_group = pdb.gimp_layer_group_new(image)
    layer_group=pdb.gimp_item_get_parent(image.layers[0])
    layer=pdb.gimp_file_load_layer(image, file)
    pdb.gimp_image_insert_layer(image,layer,layer_group,1)#(image, layer, parent, position)
    for layer in image.layers:
      pdb.gimp_item_set_visible(layer,True)
    layer = pdb.gimp_image_merge_visible_layers(image, 0)
    pdb.gimp_image_set_active_layer(image, layer)
    drawable = pdb.gimp_image_get_active_layer(image)
    # with open("E:/out.txt",'w') as outTxt:
    #   outTxt.write(outFile)
    pdb.file_dds_save(image, drawable, outFile,outFile,0,0,0,0,0,0,0)
    def runMultipleFromList(self, filenames_foreground, seperator_character):
        """
			Copy and paste the foreground image onto the background image, flatten the background image down into one layer, and
			then save the result to file.
	
	
			Parameters:
	
			NA
	
	
			Returns:
	
			NA


			Invoked by :

			runPlugin_multiple_fromList
			OverlayImageAgent.runMultipleFromFile


			Invokes :

			OverlayImageAgent.__getForegroundImageAndDrawable
			OverlayImageAgent.__displayDiagnosticData
			OverlayImageAgent.__run
			"""

        nameProcedure = "OverlayImageAgent::runMultipleFromList"

        print("%s : Enter" % (nameProcedure))

        print("%s : filenames_foreground = %s" %
              (nameProcedure, filenames_foreground))
        print("%s : seperator_character  = %s" %
              (nameProcedure, seperator_character))

        # Ascertain how many Foreground Images were passed to this Plugin.

        self.filenames_foreground = filenames_foreground.split(
            seperator_character)

        print("%s : Number of Foreground filenames = %d" %
              (nameProcedure, len(self.filenames_foreground)))

        gimp.progress_init(
            "Have got image and drawable from Background Image file")

        # Start a GIMP Undo group.
        #
        # This will allow the actions of this Plugin to be undone in one step.

        # pdb.gimp_image_undo_group_start(self.image_background)

        for filename_foreground in self.filenames_foreground:

            print("%s : filename_foreground = %s" %
                  (nameProcedure, filename_foreground))

            if path.isfile(filename_foreground):

                self.filename_foreground = filename_foreground

                print("%s : Filename Foreground image = %s" %
                      (nameProcedure, self.filename_foreground))
                print("%s : Length of filename        = %d chars" %
                      (nameProcedure, len(self.filename_foreground)))

                self.filename_result = self.__constructFilenameResult(
                    self.filename_foreground)

                self.image_background = pdb.gimp_file_load(
                    self.filename_background, self.filename_background)
                self.drawable_background = pdb.gimp_image_get_active_layer(
                    self.image_background)

                print("%s : Filename background image = %s" %
                      (nameProcedure, self.image_background.filename))

                self.__getForegroundImageAndDrawable(self.filename_foreground)

                message = "<span foreground=\"black\" style=\"italic\">" + nameProcedure + " : Processing next Foreground Image</span>"

                self.__displayDiagnosticData(message)

                self.__run()

                # Close the GIMP Images now that we have finished with them, otherwise they will use up
                # memory unnecessarily.

                pdb.gimp_image_delete(self.image_foreground)
                pdb.gimp_image_delete(self.image_background)

            else:

                print("%s : Filename Foreground image DOESN'T exist = %s" %
                      (nameProcedure, self.filename_foreground))

        # ----------------------------------------------------------------------------------------------
        # End the GIMP Undo group which was started at the beginning of this Plugin.
        # ----------------------------------------------------------------------------------------------

        # pdb.gimp_image_undo_group_end(self.image_background)

        print("%s : Exit" % (nameProcedure))
Esempio n. 16
0
def \
superimpose_image_over_another_noninteractive(

        # image,
        # drawable,
        list_filenames,
        list_filenames_superimpose
    # horizontalLocation,
    # verticalLocation
) :

    nameFunction = "superimpose_image_over_another_interactive"

    print("----------------------------------------")
    print("%s : Enter" % (nameFunction))

    IFS = ";"

    # listFiles = fileContents.split(IFS)

    listFiles = list_filenames.split(IFS)
    listFiles_superimpose = list_filenames_superimpose.split(IFS)

    print("%s : Number of elements in list = %d" %
          (nameFunction, len(listFiles)))
    print("%s : File list = %s" % (nameFunction, listFiles))

    print("%s : Number of elements in list = %d" %
          (nameFunction, len(listFiles_superimpose)))
    print("%s : File list = %s" % (nameFunction, listFiles_superimpose))

    if (len(listFiles) == 0):

        print("%s : Number of background image files = 0 : a") % (nameFunction)

        # errdialog = gtk.MessageDialog(
        #                               None,
        #                               0,
        #                               gtk.MESSAGE_ERROR,
        #                               gtk.BUTTONS_OK,
        #                               "A) You must specify at least one background image file."
        #                              )
        # errdialog.show_all()
        # errdialog.run()

        # raise Exception("You must specify at least one background image file.")

    elif (len(listFiles_superimpose) == 0):

        gimp.message(
            "B) You must specify at least one superimpose image file.")
        print("%s : Number of superimpose image files = 0 : a") % (
            nameFunction)
        # raise Exception("You must specify at least one superimpose image file.")

    # elif (len(listFiles) == 1) : and
    elif (listFiles[0] == ''):

        gimp.message("C) You must specify at least one background image file.")
        print("%s : Number of background image files = 0 : b") % (nameFunction)
        # raise Exception("You must specify at least one background image file.")

    # elif (len(listFiles_superimpose) == 1) and
    elif (listFiles_superimpose[0] == ''):

        gimp.message(
            "D) You must specify at least one superimpose image file.")
        print("%s : Number of superimpose image files = 0 : b") % (
            nameFunction)
        # raise Exception("You must specify at least one superimpose image file.")

    elif len(listFiles) != len(listFiles_superimpose):

        gimp.message(
            "E) The number of files specified must be the same for both background and superimpose images."
        )
        print(
            "%s : The number of files specified must be the same for both background and superimpose images!"
        ) % (nameFunction)
        # raise Exception("The number of files specified must be the same for both background and superimpose images!")

    indexList = 0

    for filename in listFiles:

        indexList = indexList + 1

        print("%s : ========================================" % (nameFunction))
        print("%s : Filename = %s" % (nameFunction, filename))
        print("%s : ========================================" % (nameFunction))

        if (not path.isfile(filename)):

            print("%s :    > is NOT a file" % (nameFunction))

            continue

        filename_superimpose = listFiles_superimpose[indexList - 1]

        print("%s : ========================================" % (nameFunction))
        print("%s : Filename of image to superimpose = %s" %
              (nameFunction, filename_superimpose))
        print("%s : ========================================" % (nameFunction))

        if (not path.isfile(filename_superimpose)):

            print("%s :    > is NOT a file" % (nameFunction))

        gimp.progress_init("Superimposing one image over the other")

        image = pdb.gimp_file_load(filename, filename)
        drawable = pdb.gimp_image_get_active_layer(image)

        # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one step.

        pdb.gimp_undo_push_group_start(image)

        widthImage = image.width
        heightImage = image.height

        widthDrawable = drawable.width
        heightDrawable = drawable.height

        print("Width image             = %s" % widthImage)
        print("Height image            = %s" % heightImage)
        print("Width drawable          = %s" % widthDrawable)
        print("Height drawable         = %s" % heightDrawable)
        # print("Horizontal location     = %s" % horizontalLocation)
        # print("Vertical location       = %s" % verticalLocation)
        print("Image filename          = %s" % image.filename)

        # Open the image file to be superimposed and get its drawable object.

        image_super = pdb.gimp_file_load(filename_superimpose,
                                         filename_superimpose)
        drawable_super = pdb.gimp_image_get_active_layer(image_super)

        print("Width super image             = %s" % image_super.width)
        print("Height super image            = %s" % image_super.height)
        print("Width super drawable          = %s" % drawable_super.width)
        print("Height super drawable         = %s" % drawable_super.height)

        # How many layers does the current image now contain?
        #
        # Use gimp-edit-copy and gimp-edit-paste?

        copy_result = pdb.gimp_edit_copy(drawable_super)

        if (copy_result == True):

            print("True")

        else:

            print("False")

        print("Selection copy result = %s" % copy_result)

        # pdb.gimp_drawable_update(drawable, horizontalLocation, verticalLocation, 384, 216)

        # The following operation should paste the image which is in the buffer, into a new layer of the
        # original image.

        pdb.gimp_edit_paste(drawable, True)

        widthImage = image.width
        heightImage = image.height

        widthDrawable = drawable.width
        heightDrawable = drawable.height

        print("Width image             = %s" % widthImage)
        print("Height image            = %s" % heightImage)
        print("Width drawable          = %s" % widthDrawable)
        print("Height drawable         = %s" % heightDrawable)
        # print("Horizontal location     = %s" % horizontalLocation)
        # print("Vertical location       = %s" % verticalLocation)

        # Move the

        # pdb.gimp_drawable_update()

        drawable_new = pdb.gimp_image_flatten(image)

        pdb.gimp_file_save(image, drawable_new, filename, filename)

        # End the GIMP Undo group.

        pdb.gimp_undo_push_group_end(image)

        # Close the image now that we have finished with it, otherwise it will use up memory unnecessarily.

        pdb.gimp_image_delete(image)

    # End of for loop.

    print("%s : Exit" % (nameFunction))
Esempio n. 17
0
def despeckle(fin, fout):
    image = pdb.gimp_file_load(fin, fin)
    drawable = pdb.gimp_image_get_active_layer(image)
    pdb.plug_in_despeckle(image, drawable, 3, 1, 7, 248)
    pdb.gimp_file_save(image, drawable, fout, fout)
    pdb.gimp_image_delete(image)
Esempio n. 18
0
#!/usr/bin/python

import traceback
from gimpfu import pdb, gimp
import gimpfu as gfu

infile = "test.jpg"
outfile = "out.png"
try:
    image = pdb.gimp_file_load(infile, infile, run_mode=gfu.RUN_NONINTERACTIVE)
    # w = 200
    # h = round(w * image.height / float(image.width))
    # pdb.gimp_image_scale(image, w, h)
    pdb.python_fu_super_resolution(image, image.active_layer)
    image.flatten()
    pdb.gimp_file_save(image, image.active_layer, outfile, outfile, run_mode=gfu.RUN_NONINTERACTIVE)
except:
    gimp.message("ERROR:\n" + traceback.format_exc())
pdb.gimp_quit(1)
Esempio n. 19
0
def simple_plugin(filename_background, filename_foreground, filename_result):

    nameProcedure = "simple_plugin"

    sleep_timer = 0

    counter = 1

    print("%s : Enter" % (nameProcedure))

    # ----------------------------------------------------------------------------------------------
    # Get the following from both the background and foreground image files;
    #
    #   - image
    #   - drawable
    # ----------------------------------------------------------------------------------------------

    image_background = pdb.gimp_file_load(filename_background,
                                          filename_background)
    drawable_background = pdb.gimp_image_get_active_layer(image_background)

    image_foreground = pdb.gimp_file_load(filename_foreground,
                                          filename_foreground)
    drawable_foreground = pdb.gimp_image_get_active_layer(image_foreground)

    display_diagnostics(counter, image_background, image_foreground,
                        drawable_background, drawable_foreground)

    counter = counter + 1

    gimp.progress_init("Have got image and drawable from both files")
    time.sleep(sleep_timer)

    # ----------------------------------------------------------------------------------------------
    # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one
    # step.
    # ----------------------------------------------------------------------------------------------

    pdb.gimp_image_undo_group_start(image_background)

    # ----------------------------------------------------------------------------------------------
    # Copy the foreground image.
    # ----------------------------------------------------------------------------------------------

    copy_result = pdb.gimp_edit_copy(drawable_foreground)

    print("%s : Copy result = %s" % (nameProcedure, str(copy_result)))

    gimp.progress_init("Have copied foreground image into Buffer")
    time.sleep(sleep_timer)

    # ----------------------------------------------------------------------------------------------
    # Paste the foreground image onto the background image.
    # ----------------------------------------------------------------------------------------------

    use_gimp_edit_paste_as_new = False

    if use_gimp_edit_paste_as_new:

        pdb.gimp_edit_paste(drawable_background, True)

    else:

        image_background_new = pdb.gimp_edit_paste_as_new(
            drawable_background, True)

        if (image_background_new == -1):

            print(
                "%s : Attempted to paste from the Edit buffer, but it appears to be empty."
                % (nameProcedure))

            exception_message = "\n\nAn Exception has been raised by the method;\n\n  " + \
                                nameProcedure + \
                                "\n\nThis method attempted to paste from the Edit buffer, but it appears to be empty.\n\nAs a result, this Plugin is about to terminate!"

            raise Exception(exception_message)

    gimp.progress_init(
        "Have pasted foreground image from Buffer onto background image")
    time.sleep(sleep_timer)

    display_diagnostics(counter, image_background, image_foreground,
                        drawable_background, drawable_foreground)

    counter = counter + 1

    # ----------------------------------------------------------------------------------------------
    # Flatten the modified background image down into one layer.
    # ----------------------------------------------------------------------------------------------

    drawable_background = pdb.gimp_image_flatten(image_background)

    gimp.progress_init("Have flattened the background image")
    time.sleep(sleep_timer)

    display_diagnostics(counter, image_background, image_foreground,
                        drawable_background, drawable_foreground)

    # ----------------------------------------------------------------------------------------------
    # Save the background image into a specified file.
    # ----------------------------------------------------------------------------------------------

    if use_gimp_edit_paste_as_new:

        pdb.gimp_file_save(image_background, drawable_background,
                           filename_result, filename_result)

    else:

        pdb.gimp_file_save(image_background_new, drawable_background,
                           filename_result, filename_result)

    gimp.progress_init("Have saved the background image")
    time.sleep(sleep_timer)

    # ----------------------------------------------------------------------------------------------
    # End the GIMP Undo group which was started at the beginning of this Plugin.
    # ----------------------------------------------------------------------------------------------

    pdb.gimp_image_undo_group_end(image_background)

    # ----------------------------------------------------------------------------------------------
    # Close the GIMP images now that we have finished with them, otherwise they will use up memory
    # nnecessarily.
    # ----------------------------------------------------------------------------------------------

    pdb.gimp_image_delete(image_foreground)
    pdb.gimp_image_delete(image_background)

    print("%s : Exit" % (nameProcedure))
Esempio n. 20
0
    def processList(self):

        nameMethod = self.nameClass + "::run"

        print("%s : Enter" % (nameMethod))

        # Start a GIMP Undo group, as this will allow the actions of this Plugin to be undone in one step.

        # pdb.gimp_undo_push_group_start(image)

        indexList = 0

        for filenameForeground in self.listFilenamesForeground:

            indexList = indexList + 1

            # self.checkFiles(filename, filenameOverlay)

            self.imageBackground = pdb.gimp_file_load(self.filenameBackground,
                                                      self.filenameBackground)
            self.drawableBackground = pdb.gimp_image_get_active_layer(
                self.imageBackground)

            self.imageForeground = pdb.gimp_file_load(filenameForeground,
                                                      filenameForeground)
            self.drawableForeground = pdb.gimp_image_get_active_layer(
                self.imageForeground)

            print("%s : Processing ..." % (nameMethod))
            print("%s :   Background image = %s" %
                  (nameMethod, self.filenameBackground))
            print("%s :   Overlay    image = %s" %
                  (nameMethod, filenameForeground))

            # Display information about both of the current images.

            self.displayImageData()

            # How many layers does the current image now contain?
            #
            # Use gimp-edit-copy and gimp-edit-paste?

            self.overlayImage()

            # Move the

            # pdb.gimp_drawable_update()

            # self.drawableNew = pdb.gimp_image_flatten(self.imageNew)

            pdb.gimp_file_save(self.imageForeground, self.drawableForeground,
                               filenameForeground, filenameForeground)

            # Close the images now that we have finished with it, otherwise they will use up memory unnecessarily.

            pdb.gimp_image_delete(self.imageForeground)
            pdb.gimp_image_delete(self.imageBackground)

            # End of for loop.

        # End the GIMP Undo group.

        # pdb.gimp_undo_push_group_end(image)

        print("%s : Enter" % (nameMethod))
Esempio n. 21
0
def \
scale_and_set_size_file_noninteractive(

        horizontalResolution,
        verticalResolution,
        interpolationMode,    # 0,1,2,3 : 3 = INTERPOLATION_LANCZOS
        listFiles
) :

    nameFunction = "scale_and_set_size_noninteractive"

    print("%s : Enter" % (nameFunction))

    print("%s : Checking if Interpolation mode value is valid" %
          (nameFunction))

    if (interpolationMode == INTERPOLATION_LANCZOS):

        interpolationMode = 3

    # if ((int(interpolationMode) < 0) or (int(interpolationMode) > 3)) :

    else:

        print("%s : Interpolation mode value is NOT valid = %s" %
              (nameFunction, str(interpolationMode)))

        raise Exception("Invalid value for parameter : interpolationMode")

    print("%s : Interpolation mode value IS valid = %s" %
          (nameFunction, interpolationMode))

    debug = False

    fileHandle = open(listFiles, "r")

    filesList = fileHandle.read()

    fileHandle.close()

    listFiles = filesList.split("\n")

    print("%s : Number of elements in list = %d" %
          (nameFunction, len(listFiles)))
    print("%s : File list = %s" % (nameFunction, listFiles))

    for filename in listFiles:

        try:

            print("%s : ========================================" %
                  (nameFunction))
            print("%s : Filename = %s" % (nameFunction, filename))
            print("%s : ========================================" %
                  (nameFunction))

            if (not path.isfile(filename)):

                print("%s :    > is NOT a file" % (nameFunction))

                continue

            # Open the image file and get its drawable object.

            image = pdb.gimp_file_load(filename, filename)
            drawable = pdb.gimp_image_get_active_layer(image)

            #

            scale_and_set_size_interactive(image, drawable,
                                           horizontalResolution,
                                           verticalResolution,
                                           interpolationMode, filename)

            # Close the image now that we have finished with it, otherwise it will use up memory unnecessarily.

            pdb.gimp_image_delete(image)

            print("%s : Exit" % (nameFunction))

        except:

            print("########################################")
            print("########################################")
            print("Something went wrong while attempting to")
            print("process the previous file;              ")
            print("")
            print("  %s" % (filename))
            print("")
            print("########################################")
            print("########################################")
Esempio n. 22
0
def flip(file):
    image = pdb.gimp_file_load(file, file)
    drawable = pdb.gimp_image_get_active_layer(image)
    pdb.gimp_image_flip(image, ORIENTATION_HORIZONTAL)
    pdb.gimp_file_save(image, drawable, file, file)
    pdb.gimp_image_delete(image)
def runPlugin(

  filename_input,
  filename_result,
  filename_face_detect,
  filename_cascade,
  colour_rectangle
) :

	"""
	This function gets registered with GIMP as it implements the following Plugin : Detect Faces

	This function will attempt to detect faces within an image, and any faces which it does detect it will frame with a rectangle. Once it has finished doing this,
	it will save the resulting image into a file.


	Parameters:

	filename_input (String) :
	The filename of the input image.

	filename_result (String) :
	The filename of the file into which the resulting image will be saved.

	filename_cascade (String) :
	The filename of the Harr Transform Cascade file which should be used to detect the faces.

	colour_rectangle (String) :
	The colour to use for the face framing rectangles.


	Returns:

	NA


	Invoked by :

	GIMP


	Invokes:

	None
	"""


	nameProcedure = "runPlugin_single"


	print("%s : Enter" % (nameProcedure))

	print("%s : %s" % (nameProcedure, filename_input))
	print("%s : %s" % (nameProcedure, filename_result))
	print("%s : %s" % (nameProcedure, colour_rectangle))

	# Open and display withih GIMP, the input image.

	image_input = pdb.gimp_file_load(filename_input, filename_input)

	pdb.gimp_display_new(image_input)

	# "Clean" the following image by setting its Dirty (Edit) counter to 0. 
	#
	# If this is not done and the user attempts to close the image, then GIMP will complain that the image has
	# unsaved changes.

	pdb.gimp_image_clean_all(image_input)

	# Run the Face detection code on the Input image.
	#
	# At the time this Plugin was developed, Python and its Plugins could only be implemented using Python 2; whereas the Face detection code has 
	# unfortunately been implemented using Python 3 source code and modules. Therefore, if this Plugin were to try and run the Face detection code
	# directly, then the Python Runtime system would fail. It is for this reason that the Face detection code has been invoked below as a separate
	# processs.

	subprocess.call(
	  [
	   "python3",
	   filename_face_detect,
	   filename_cascade,
	   filename_input,
	   filename_result,
	   colour_rectangle
	  ]
	)

	# Open and display within GIMP, the result image.

	image_result = pdb.gimp_file_load(filename_result, filename_result)

	pdb.gimp_display_new(image_result)

	# "Clean" the following image by setting its Dirty (Edit) counter to 0. 
	#
	# If this is not done and the user attempts to close the image, then GIMP will complain that the image has
	# unsaved changes.

	pdb.gimp_image_clean_all(image_result)

	print("%s : Exit" % (nameProcedure))
Esempio n. 24
0
def despeckle(fin, fout):
    image = pdb.gimp_file_load(fin, fin)
    drawable = pdb.gimp_image_get_active_layer(image)
    pdb.plug_in_despeckle(image, drawable, 3, 1, 7, 248)
    pdb.gimp_file_save(image, drawable, fout, fout)
    pdb.gimp_image_delete(image)
Esempio n. 25
0
from gimpfu import pdb

filename = "hall_of_fame_large.xcf"
image = pdb.gimp_file_load(filename, filename)
pdb.gimp_image_scale(image, 1280, 800)
outfilename = "hall_of_fame.png"
layer = pdb.gimp_image_merge_visible_layers(image, 1)
pdb.gimp_file_save(image, layer, outfilename, outfilename)
Esempio n. 26
0
def layerToDDS(timg, tdrawable, file, argumentFile, outFolder, byName,
               scaleBool, scaleTo):  #, argumentFile,hmm,blub):
    # num_layers, layer_ids = pdb.gimp_image_get_layers(image)
    # with open("E:/out.txt",'w') as outTxt:
    # outTxt.write(str(os.getcwd()))
    outFolder = os.path.dirname(file) + "/" + outFolder
    if not os.path.exists(outFolder):
        os.makedirs(outFolder)
    if argumentFile.lower() == "all":
        image = pdb.gimp_file_load(file, file)
        fileContent = []
        for layer in image.layers:
            layername = pdb.gimp_item_get_name(layer)
            fileContent.append(layername + " " + layername)
            byName = True
    else:
        with open(argumentFile, 'r') as argfile:
            fileContent = [line for line in argfile]
    for l in fileContent:
        image = pdb.gimp_file_load(file, file)
        if scaleBool:
            if scaleTo:
                pdb.gimp_image_resize(image, 52, 52, -26, -26)
            else:
                pdb.gimp_image_scale(image, 52, 52)
        line = shlex.split(l)
        outFile = outFolder + "/" + line[0]
        if outFile[-4:] != ".dds":
            outFile += ".dds"
        for layer in image.layers:
            #   layer = pdb.gimp_image_get_layer_by_name(image, id)
            pdb.gimp_item_set_visible(layer, False)
        layers = []
        for i, word in enumerate(line[1:]):
            if byName:
                if word[:4] == "MOVE":
                    word2 = word[5:]
                    layer = pdb.gimp_image_get_layer_by_name(image, word2)
                    # pdb.gimp_item_set_visible(layer,True)
                    pdb.gimp_layer_scale(layer, 40, 40, False)
                    pdb.gimp_image_set_active_layer(image, layer)
                    drawable = pdb.gimp_image_get_active_layer(image)
                    if word[4] == "L":
                        pdb.script_fu_move_layer_to(image, drawable, -2.5, 5)
                    elif word[4] == "R":
                        pdb.script_fu_move_layer_to(image, drawable, 17.5, 5)
                    line[1 + i] = line[1 + i][5:]
                    # pdb.gimp_item_set_visible(layer,False)

        for word in line[1:]:
            #outTxt.write(word+"\n")
            #layers.append(pdb.gimp_layer_copy(image.layers[int(word)],False))
            #pdb.gimp_image_insert_layer(image, layer,image.layers[int(word)], 0)
            try:
                if byName:
                    pdb.gimp_item_set_visible(
                        pdb.gimp_image_get_layer_by_name(image, word), True)
                else:
                    pdb.gimp_item_set_visible(image.layers[int(word)], True)
            except:
                pdb.gimp_message("Error parsing line " + " ".join(line) +
                                 ". Probably a missing/invalid item")
                raise
        if scaleBool and scaleTo:
            for word in line[2:]:
                if byName:
                    layer = pdb.gimp_image_get_layer_by_name(image, word)
                else:
                    layer = image.layers[int(word)]
                pdb.gimp_layer_scale(layer, scaleTo, scaleTo, False)
                pdb.gimp_layer_resize(layer, 52, 52, -1, -1)

        # for layer in layers:
        #   outTxt.write("{!s}".format(layer))
        #   pdb.gimp_item_set_visible(layer, True)
        #pdb.gimp_item_set_visible(image.layers[3], True)
        #pdb.gimp_item_set_visible(image.layers[5], True)
        layer = pdb.gimp_image_merge_visible_layers(image, 0)
        pdb.gimp_image_set_active_layer(image, layer)
        drawable = pdb.gimp_image_get_active_layer(image)
        for layerIt in image.layers:
            if layerIt != layer or not scaleTo:
                pdb.gimp_layer_resize_to_image_size(layerIt)
        try:
            pdb.file_dds_save(image, drawable, outFile, outFile, 0, 0, 0, 0, 0,
                              0, 0)
        except:
            pdb.file_dds_save(image, drawable, outFile, outFile, 0, 0, 0, 0, 0,
                              0, 0, 0, 0, 0, 0, 0, 0)