Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Help! Python loop for the mentally challenged.
#1
I have channels, named 0 to 9.
To create layers 0 to 9, I can repeat the code, changing "0" to "1", "2", etc. and it works perfectly.
I would like to make a loop to carry out this process, but everything I have tried has given me errors and searching the internet hasn't provided any examples for me to follow.

An example of how to do this (ideally with a detailed explanation) would be appreciated and perhaps would help others.

david.

Code:
#create layer with 0 as mask
    
    pdb.gimp_image_select_item(image,CHANNEL_OP_REPLACE,channel0)
    layer_add = pdb.gimp_layer_new_from_drawable(layer,image)
    pdb.gimp_image_insert_layer(image,layer_add,None,0)
    pdb.gimp_item_set_name(layer_add,"0")
    pdb.gimp_layer_create_mask(layer_add,ADD_MASK_SELECTION)
    mask = pdb.gimp_layer_create_mask(layer_add,ADD_MASK_SELECTION)
    pdb.gimp_layer_add_mask(layer_add,mask)
    pdb.gimp_image_remove_channel(image,channel0)
Reply
#2
If the channels named 0 to 9 are the only channels in the image, you can iterate on a copy of the channels list:

Code:
for channel in image.channels[:]:
 pdb.gimp_image_select_item(image, CHANNEL_OP_REPLACE, channel)
 layer_add = pdb.gimp_layer_new_from_drawable(layer, image)
 pdb.gimp_image_insert_layer(image, layer_add, None, 0)
 pdb.gimp_item_set_name(layer_add, channel.name)
 mask = pdb.gimp_layer_create_mask(layer_add, ADD_MASK_SELECTION)
 pdb.gimp_layer_add_mask(layer_add, mask)
 pdb.gimp_image_remove_channel(image, channel)
image.channels gives the list of channels in the image.
image.channels[:] creates a copy of that list (since you delete the channel at the end of the loop, you need to work on a copy of the list)
channel.name gives the name of the channel as string
Reply
#3
tmanni,

Many thanks for your reply.
I did a cut & paste of your code into my script and it worked perfectly. Now I must study it carefully so that I can do something similar in another part of the same script.
It also helps me to understand a little more about python, although I suspect this "dog" is much to old to learn new tricks!

david.
Reply


Forum Jump: