Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to make a mask from a selection?
#1
Hi there, I am working on extending GIMP with AI functions. I ditched Photoshop lately and my pals at the Photo Club keep telling me that I am a fool to have ditched PS with all it's nice AI functions. They shouldn't say that to me...

At this moment I've got AI Remove Background working, using IOPaint that runs locally on my laptop. It still needs some fine tuning, but it works.

Now I am working on 'inpaint' (filling a selection with a generated background). I am struggling now how to make a mask from a selection. The GIMP API has many procedures, but just copying a selection seems not to be easy. Is there anyone who has some experience with this?


P.S. I am new to Gimp Forum, so maybe I missed earlier questions/discussions like this.
Reply
#2
(02-07-2026, 08:54 AM)ersc57 Wrote: Hi there, I am working on extending GIMP with AI functions. I ditched Photoshop lately and my pals at the Photo Club keep telling me that I am a fool to have ditched PS with all it's nice AI functions. They shouldn't say that to me...

At this moment I've got AI Remove Background working, using IOPaint that runs locally on my laptop. It still needs some fine tuning, but it works.

Now I am working on 'inpaint' (filling a selection with a generated background). I am struggling now how to make a mask from a selection. The GIMP API has many procedures, but just copying a selection seems not to be easy. Is there anyone who has some experience with this?


P.S. I am new to Gimp Forum, so maybe I missed earlier questions/discussions like this.

Layer > Mask > Add layer mask, chose "Selection"
Reply
#3
(02-07-2026, 03:23 PM)Scallact Wrote:
(02-07-2026, 08:54 AM)ersc57 Wrote: Hi there, I am working on extending GIMP with AI functions. I ditched Photoshop lately and my pals at the Photo Club keep telling me that I am a fool to have ditched PS with all it's nice AI functions. They shouldn't say that to me...

At this moment I've got AI Remove Background working, using IOPaint that runs locally on my laptop. It still needs some fine tuning, but it works.

Now I am working on 'inpaint' (filling a selection with a generated background). I am struggling now how to make a mask from a selection. The GIMP API has many procedures, but just copying a selection seems not to be easy. Is there anyone who has some experience with this?


P.S. I am new to Gimp Forum, so maybe I missed earlier questions/discussions like this.

Layer > Mask > Add layer mask, chose "Selection"

Sorry, I must have been unclear. I want to create a mask from a selection using python code. I would very much like to know which gimp procedures to use for achieving this. I am thinking of edit_copy and edit_paste_new_image, but the first has a drawable is argument and the second an image. So maybe it's not straightforward.
Reply
#4
Caveat, I can not write python3 to save my life.

You could look at an existing python plugin that creates a mask https://gimpchat.com/viewtopic.php?f=9&t=21432#p295051

maybe a hint in there.
Reply
#5
(02-07-2026, 09:18 PM)thatersc57 Wrote: Sorry, I must have been unclear. I want to create a mask from a selection using python code. I would very much like to know which gimp procedures to use for achieving this. I am thinking of edit_copy and edit_paste_new_image, but the first has a drawable is argument and the second an image. So maybe it's not straightforward.

I think I already did that, or something similar. For a start, it's good to know that  masks and selection are actually just channels with special purpose.So, all methods for channels apply.

I can look into it tomorrow if you still need it. Now I have to go to sleep. ;-)
Reply
#6
(02-08-2026, 02:13 AM)Scallact Wrote:
(02-07-2026, 09:18 PM)thatersc57 Wrote: Sorry, I must have been unclear. I want to create a mask from a selection using python code. I would very much like to know which gimp procedures to use for achieving this. I am thinking of edit_copy and edit_paste_new_image, but the first has a drawable is argument and the second an image. So maybe it's not straightforward.

I think I already did that, or something similar. For a start, it's good to know that  masks and selection are actually just channels with special purpose.So, all methods for channels apply.

I can look into it tomorrow if you still need it. Now I have to go to sleep. ;-)

Hi Scallact,

This is what I am thinking of...

Purpose: select an aera of a layer which should be filled with a new background by IOPaint.

what I am intending to do is:
copy the active layer to a new image (using edit_copy & edit_paste_as_new_image)
save this image to pass it on to IOPaint lateron
make the new image background black (using ?)
copy the selection to the new image (using image_get_selecten & save_selection)
make the selection white (using ?)
so then we have created a mask.
save this mask to disk (using an image)
Then feed the new image saved earlier and the mask to IOPaint
Insert the returned layer in the current image above the active layer
Set the original active layer to non-visible.

I don't know if this will work. Sometimes GIMP does not allow copying items from one image to another.
And how to make a selection white?


If you have done something like this before, I would appreciate it when you were able to share it. 
If it something like it, but not exactly, I still would like to see it as an example piece of code.
If it can be done easier, then please tell me your suggestions.

Thankx in advance!

P.S. I used to program a lot in C appr. 35 years ago. Python is new for me, so I'm still learning.

(02-07-2026, 10:04 PM)rich2005 Wrote: Caveat, I can not write python3 to save my life.

You could look at an existing python plugin that creates a mask https://gimpchat.com/viewtopic.php?f=9&t=21432#p295051

maybe a hint in there.

Thanx, rich2005. I will look at this example. Found the _mask_layer procedure and will study it. Looks like a nicely structured, though rather complicated, program.
Reply
#7
(02-08-2026, 02:15 PM)ersc57 Wrote: Hi Scallact,

This is what I am thinking of...

Purpose: select an aera of a layer which should be filled with a new background by IOPaint.

what I am intending to do is:
copy the active layer to a new image (using edit_copy & edit_paste_as_new_image)
save this image to pass it on to IOPaint lateron
make the new image background black (using ?)
copy the selection to the new image (using image_get_selecten & save_selection)
make the selection white (using ?)
so then we have created a mask.
save this mask to disk (using an image)
Then feed the new image saved earlier and the mask to IOPaint
Insert the returned layer in the current image above the active layer
Set the original active layer to non-visible.

I don't know if this will work. Sometimes GIMP does not allow copying items from one image to another.
And how to make a selection white?

Ok, I think you will have to clear up some terms used here. Also, I don't fully understand the logic behind your steps yet, and I've got the feeling that you're over complicating it. So I can't give you detailed commands for every step, because you might just not end up anywhere. ;-)

First, terminology: 
What do you mean by "mask"? Apparently, it's not about a GIMP layer mask. Is it a mask that you pass to IOPaint ? Can you describe what this mask looks like? Is it a typical black/white layer that serves as mask (but still a layer for GIMP)?
"Make the selection white". You don't make a selection white, you fill it with white, on a specific drawable (a drawable can be a layer, a layer mask, a channel, etc...)

Steps:
If I understood the mask thing right, why not create it on the first image, where you already have the selection active? This would save you the transfer of the selection to another image.
Even more simplification: since apparently you must save an image to the disk (and the mask I guess?), why not do it from the original image as well? I don't know, just suggestions.
Reply
#8
(02-08-2026, 03:23 PM)Scallact Wrote:
(02-08-2026, 02:15 PM)ersc57 Wrote: Hi Scallact,

This is what I am thinking of...

Purpose: select an aera of a layer which should be filled with a new background by IOPaint.

what I am intending to do is:
copy the active layer to a new image (using edit_copy & edit_paste_as_new_image)
save this image to pass it on to IOPaint lateron
make the new image background black (using ?)
copy the selection to the new image (using image_get_selecten & save_selection)
make the selection white (using ?)
so then we have created a mask.
save this mask to disk (using an image)
Then feed the new image saved earlier and the mask to IOPaint
Insert the returned layer in the current image above the active layer
Set the original active layer to non-visible.

I don't know if this will work. Sometimes GIMP does not allow copying items from one image to another.
And how to make a selection white?

Ok, I think you will have to clear up some terms used here. Also, I don't fully understand the logic behind your steps yet, and I've got the feeling that you're over complicating it. So I can't give you detailed commands for every step, because you might just not end up anywhere. ;-)

First, terminology: 
What do you mean by "mask"? Apparently, it's not about a GIMP layer mask. Is it a mask that you pass to IOPaint ? Can you describe what this mask looks like? Is it a typical black/white layer that serves as mask (but still a layer for GIMP)?
"Make the selection white". You don't make a selection white, you fill it with white, on a specific drawable (a drawable can be a layer, a layer mask, a channel, etc...)

Steps:
If I understood the mask thing right, why not create it on the first image, where you already have the selection active? This would save you the transfer of the selection to another image.
Even more simplification: since apparently you must save an image to the disk (and the mask I guess?), why not do it from the original image as well? I don't know, just suggestions.

Hi Scallact,

thank you for thinking with me. You may be right that I overcomplicate things. That's why I was looking for some help.

Terminology: 
You are right, by mask I mean an image with one layer that is pure black with a selection that is pure white. This is one of the input files for IOPaint inpaint.
The selection should indeed be filled with white.

Purpose:
The intention is to perform the 'inpaint with IOPaint' command in GIMP on the active layer of the active image. This layer should contain a selection. IOPaint will fill the selection with a generated background and I want the new layer with this filled selection to be inserted just above the current layer, while setting the visibility of the current layer to False. The newly inserted layer becomes the active layer.

Limitations:
Saving files to disk is needed to pass them on to IOPaint, as IOPaint is running in a sandboxed Conda environment.
The active image should not be altered in any way, expect for inserting the new layer in the end.
This command should only affect the active layer of the active image (in fact even not that, as the original layer will stay in place, see Purpose).
In GIMP a layer can only belong to one image, so we will have to duplicate a layer to get the same layer in another image. But maybe we can do something different using selections?

Steps:
1 Save active layer from the active image to a PNG temp file
  This already works.

2 Make a "mask" from the selection and save this as second temp file.
  This is the tricky part for me.
  Can I do this from the original image without changing this original image?

3 Feed both temp files to IOPaint
  I know how to do this.

4 Insert resulting layer in original image
  I know how to do this.

5 Toggle visibility of original active layer
  I know how to do this.

Most steps are (almost) equal to the steps I needed for Remove_Background with IOPaint.
That plugin works.
The only issue for me is step 2 - Making the black & white "mask" temp file. 

Is this more clear?


P.S. Rich2005 has directed me to an example plugin. I appreciate that and am looking into it, but it needs some studying as it is a very structured but also complex plugin. I would be very happy with some other input on this matter. :-)
Reply
#9
[quote='ersc57' pid='46597' dateline='1770654820']

Please respect the forum and post in English and learn not to quote over-and-over.

Not python as OP wants but might be useful although, does not look like for Gimp 3

Your main difficulty (Step 2) is solved quite easily by creating a temporary dummy image.
How to create a mask from a selection (Step 2)
To create a mask that does not change the overall image, you need to temporarily create a new image of the same size in GIMP's memory, fill it with black, turn the selection white, and save it.
Here is the logic in Script-Fu (SCM) that does just that:

Code:
(let* (
     (width  (car (gimp-image-width image)))
     (height (car (gimp-image-height image)))
     ; 1. Создаем временное изображение в памяти (не отображаем его)
     (mask-img (car (gimp-image-new width height GRAY)))
     (mask-layer (car (gimp-layer-new mask-img width height GRAY-IMAGE "Mask" 100 NORMAL-MODE)))
     )
 
 (gimp-image-insert-layer mask-img mask-layer 0 -1)

 ; 2. Заливаем всё черным (фон маски)
 (gimp-context-set-background '(0 0 0))
 (gimp-drawable-fill mask-layer BACKGROUND-FILL)

 ; 3. Переносим выделение из основного изображения в маску
 ; Копируем выделение через канал
 (let ((selection (car (gimp-selection-save image))))
   (gimp-image-select-item mask-img CHANNEL-OP-REPLACE selection)
   
   ; 4. Заливаем выделенное белым
   (gimp-context-set-foreground '(255 255 255))
   (gimp-drawable-edit-fill mask-layer FOREGROUND-FILL)
   
   ; Удаляем временный канал
   (gimp-image-remove-channel image selection)
 )

 ; 5. Экспортируем маску
 (file-png-save-defaults RUN-NONINTERACTIVE mask-img mask-layer "C:/temp/mask.png" "mask.png")

 ; 6. Удаляем временное изображение из памяти, чтобы не занимать RAM
 (gimp-image-delete mask-img)
)


P.S. «...тому не нужно далеко ходить, у кого черт за плечами», — ответил Пацюк
Reply
#10
Hi,

I'm not sure that I understand the problem, but I wrote some code for exporting a selection for a mask. The original image is modified but is then restored back to its original state. I haven't tested the code, so there could be bug(s).

Code:
#!/usr/bin/env python3
import gi
gi.require_version('Gimp', '3.0')
from gi.repository import Gegl, Gimp          # noqa


def export_selection_as_white_layer(image):
   """
   Given an image, export the current selection as a new image
   from the current selection filled with white and having a black background.

   Steps:
   1. Create a new image to hold a mask-like layer.

   2. Create a white selection layer.

   3. Transfer the white selection layer to the new image.

   4. Export the new image as a PNG file with its alpha layer turned off.

   5. Restore the original image back to its original state.

   image: Gimp.Image
       Has a selection that is to be exported a mask-like layer.
   """
   # Create a temporary image.
   w, h = image.get_width(), image.get_height()
   temp_image = Gimp.Image.new(w, h, Gimp.ImageBaseType.RGB)
   display = Gimp.Display.new(temp_image)

   # Create a new layer for a white selection on top of the original image.
   white_selection_layer = Gimp.Layer.new(
       image,
       "White Selection Layer",
       w,
       h,
       Gimp.ImageType.RGBA_IMAGE,
       100.,
       Gimp.LayerMode.NORMAL
   )

   image.insert_layer(white_selection_layer, None, 0)

   # Fill the selection with white.
   Gimp.context_set_opacity(100.)
   Gimp.context_set_paint_mode(Gimp.LayerMode.NORMAL)
   Gimp.context_set_foreground(Gegl.Color.new('white'))
   white_selection_layer.edit_fill(Gimp.FillType.FOREGROUND)

   # Create a new layer from the white selection layer.
   layer_copy = Gimp.Layer.new_from_drawable(
       white_selection_layer, temp_image
   )

   temp_image.insert_layer(layer_copy, None, 0)

   # Export the temp-image as a PNG file and without an alpha
   # so that the background is black.
   # * Insert export PNG code here. *

   # Remove the temporary layer from the original image.
   image.remove_layer(white_selection_layer)

   # Delete the new image.
   # display.delete()

I've left the export PNG code out as you've stated you already have that figured-out.

Charles


Attached Files
.zip   export_black_and_white_selection.zip (Size: 988 bytes / Downloads: 14)
Reply


Forum Jump: