def jetkiller(img, colormap, ignore_gray): img.undo_group_start() gimp.progress_init("Executing Jet Killer ...") src_layer = img.active_layer w = src_layer.width h = src_layer.height dst_layer = gimp.Layer(img, src_layer.name + " - Jet Killer", w, h, gimpenums.RGBA_IMAGE) dst_layer.set_offsets( *src_layer.offsets) # at the same position as the source img.add_layer(dst_layer) # on top by default input_cmap = get_colormap("jet") output_cmap = get_colormap(colormap) def raw_convert_pixel(px): # Get nearest color from input colormap and return # corresponding color in output colormap dr = input_cmap[:, 0] - ord(px[0]) dg = input_cmap[:, 1] - ord(px[1]) db = input_cmap[:, 2] - ord(px[2]) dist = dr * dr + dg * dg + db * db idx = np.argmin(dist) return "".join([chr(j) for j in output_cmap[idx]]) cache = {} def convert_pixel(px): if px not in cache: cache[px] = raw_convert_pixel(px) return cache[px] gimp.tile_cache_ntiles(_tile_cache_size) src_rgn = src_layer.get_pixel_rgn(0, 0, src_layer.width, src_layer.height, False, False) dst_rgn = dst_layer.get_pixel_rgn(0, 0, dst_layer.width, dst_layer.height, True, True) for x in xrange(src_layer.width): for y in xrange(src_layer.height): pixel = src_rgn[x, y] if not ignore_gray or (pixel[0] != pixel[1] or pixel[1] != pixel[2]): new_rgb_pixel = convert_pixel(pixel[0:3]) if len(pixel) == 4: # has an alpha channel new_rgba_pixel = new_rgb_pixel + pixel[3] else: new_rgba_pixel = new_rgb_pixel + chr(255) dst_rgn[x, y] = new_rgba_pixel gimp.progress_update(float(x) / src_layer.width) # update progress bar dst_layer.flush() dst_layer.merge_shadow() dst_layer.update(0, 0, dst_layer.width, dst_layer.height) gimp.pdb.gimp_progress_end() # important for non-interactive mode gimp.displays_flush() img.undo_group_end()
def python_ndsexport_rgba(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) width = drawable.width height = drawable.height fileOut = open(filename, "wb") ## TODO : Use pixelregion instead of gimp_drawable_get_pixel #pr = drawable.get_pixel_rgn(0, 0, width, height, False, False) gimp.progress_init( _("Saving as Nintendo DS RGBA (raw 16 bit color with 1 bit alpha)")) fileOut.write("RGBA") # file header fileOut.write(struct.pack("<II", width, height)) bytePartCount = 0 for y in range(0, height): for x in range(0, width): (channels, pixel) = pdb.gimp_drawable_get_pixel(drawable, x, y) # TO OPTIMIZE, very slow color = rgb32toint16(pixel[0], pixel[1], pixel[2]) if channels > 3 and pixel[3] > 128: color |= (1 << 15) fileOut.write(struct.pack("<H", color)) gimp.progress_update(float(x + y * width) / (width * height)) gimp.progress_update(1) fileOut.close()
def save_wavefile(img, layer, filename, raw_filename): gimp.progress_init("Exporting Wavefile ...") progress = 0.0 progress_offset = 0.05 # Create Buffer # Read the file. buf = Buffer(layer.width * layer.height) gimp.progress_update(progress_offset) (X, Y) = (layer.width, layer.height) progress_step = (1.0 - progress_offset) / float(Y) for y in range(Y): gimp.progress_update(-progress_offset + float(y) / float(Y)) pixels = getRow(layer, y) values = None # Convert color to gray if len(pixels) == 3: values = pixels[0] * pixels[0] \ + pixels[1] * pixels[1] \ + pixels[2] * pixels[2] values.sqrt() elif len(pixels) == 1: values = pixels[0] buf << values # All pixels are now in the Buffer normalize and center about zero. mmax = buf.getMax() distance = mmax - buf.getMin() l = mmax - 0.5 * distance buf -= l buf.normalize() # Scale a bit so it's not loud. buf *= 0.66 # Write out to file. buf >> filename # Add an ID3v1 tag t = ID3v1Tag() t.title = "GIMP+Python+Nsound" t.comment = "w=%d h=%d" % (X, Y) t.write(filename) gimp.progress_update(1.0)
def python_ndsexport_rgb256(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) width = drawable.width height = drawable.height fileOut = open(filename, "wb") ## TODO : Use pixelregion instead of gimp_drawable_get_pixel #pr = drawable.get_pixel_rgn(0, 0, width, height, False, False) gimp.progress_init(_("Saving as Nintendo DS RGB256 (256 colors palette)")) imageIndex, indexedDrawable = index_copy_of_image(img, 16) fileOut.write("256c") # file header fileOut.write(struct.pack("<II", width, height)) for y in range(0, height): for x in range(0, width): (channels, pixel) = pdb.gimp_drawable_get_pixel(indexedDrawable, x, y) # TO OPTIMIZE, very slow value = pixel[0] fileOut.write(struct.pack("<B", value)) gimp.progress_update( float((x + y * width) * 0.8) / (width * height)) createPalette(imageIndex, 256, fileOut) gimp.progress_update(1) fileOut.close() gimp.delete(img)
def do_export_pcd8544(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) gimp.pdb.gimp_message_set_handler( ERROR_CONSOLE ) lcdwidth = 84 lcdheight = 48 lcdrows = 6 rowpixels = lcdheight/lcdrows width = drawable.width height = drawable.height if (width < lcdwidth or height < lcdheight): raise Exception("Image too small (%dpx * %dpx, expected %dpx * %dpx)" % (width, height, lcdwidth, lcdheight)) fileOut = open(filename,"w") #remove path from filename and extension filename = "".join([c for c in os.path.splitext(os.path.basename(filename))[0] if re.match(r'\w', c)]) filename = "LCDIMAGE" if filename == "" else filename gimp.progress_init(_("Saving as PCD8544 C header (84x48x1)")) fileOut.write("#ifndef %s\n" % filename.upper() ) fileOut.write("#define %s\n" % filename.upper() ) fileOut.write("\n") fileOut.write("const uint8_t %s[] = {\n" % filename ) index = 0 # from https://github.com/adafruit/Adafruit_Nokia_LCD/blob/master/Adafruit_Nokia_LCD/PCD8544.py#L157 for row in range(lcdrows): # Iterate through all 83 x axis columns. for x in range(lcdwidth): # Set the bits for the column of pixels at the current position. bits = 0 # Don't use range here as it's a bit slow for bit in [0, 1, 2, 3, 4, 5, 6, 7]: (channels,pixel) = pdb.gimp_drawable_get_pixel(drawable, x, (row*rowpixels+7-bit)) bits = bits << 1 bits |= 1 if pixel[0] == 0 else 0 # Update buffer byte and increment to next byte. index += 1 fileOut.write("0x%02X%s" % (bits, ("" if (lcdwidth * lcdheight) == index else ", "))) gimp.progress_update(float(index/(lcdwidth*lcdheight))) fileOut.write( "\n" ) fileOut.write("};\n" ) fileOut.write("#endif /* %s */\n" % filename.upper() ) gimp.progress_update(1) fileOut.close()
def hello(): """Mostra a mensagem Olá Mundo em um quadro de mensagem modal""" gimp.progress_init("Olá Mundo") dlg = gtk.MessageDialog(type=gtk.MESSAGE_INFO, buttons=gtk.BUTTONS_CLOSE) dlg.set_markup("Olá Mundo!") dlg.run() dlg.destroy() while gtk.events_pending(): gtk.main_iteration() for i in range(100): gimp.progress_update(i / 100.) time.sleep(.05) gimpfu.pdb.gimp_progress_end()
def python_ks0108export(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) width = drawable.width height = drawable.height fileOut = open(filename,"w") #remove path from filename and extension i = filename.rfind("/") p = filename.rfind(".") if ( i >= 0 ): if ( p == -1 ): filename = filename[i+1:len(filename) ] else: filename = filename[i+1:p ] gimp.progress_init(_("Saving as KS0108 (1 bit color)")) fileOut.write("#ifndef %s\n" % filename.upper() ) fileOut.write("#define %s\n" % filename.upper() ) fileOut.write("\n") fileOut.write("#include <avr/pgmspace.h>\n") fileOut.write("\n") fileOut.write("#define %s_WIDTH" % filename.upper()); fileOut.write(" %d\n" % width); fileOut.write("#define %s_HEIGHT" % filename.upper()); fileOut.write(" %d\n" % height); fileOut.write("\n") fileOut.write("static const uint8_t %s_data[] PROGMEM = {\n" % filename ) for y in range(0,height, 8): for x in range(0,width, 8): for xx in range(0,8): byte = 255 for yy in range(0,8): (channels,pixel) = pdb.gimp_drawable_get_pixel(drawable,x + xx, y + yy) byte = byte & ~( pixel[0] << yy ) fileOut.write("0x%02X, " % byte) gimp.progress_update(float(x+y*width)/(width*height)) fileOut.write( "\n" ) fileOut.write("};\n" ) fileOut.write("#endif /* %s */\n" % filename.upper() ) gimp.progress_update(1) fileOut.close()
def python_ks0108export(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) width = drawable.width height = drawable.height fileOut = open(filename,"w") #remove path from filename and extension i = filename.rfind("/") p = filename.rfind(".") if ( i >= 0 ): if ( p == -1 ): filename = filename[i+1:len(filename) ] else: filename = filename[i+1:p ] gimp.progress_init(_("Saving as HEX (1 bit color)")) fileOut.write("#ifndef %s\n" % filename.upper() ) fileOut.write("#define %s\n" % filename.upper() ) fileOut.write("\n") fileOut.write("int %sWidth = " % filename) fileOut.write("%d;" % width) fileOut.write("\n") fileOut.write("int %sHeight = " % filename) fileOut.write("%d;" % height) fileOut.write("\n\n") fileOut.write("static unsigned char __attribute__ ((progmem)) %s[] = {\n" % filename ) for y in range(0, height): for x in range(0, width, 8): byte = 0 for xx in range(0, 8): (channels,pixel) = pdb.gimp_drawable_get_pixel(drawable,x + xx, y) byte = byte | ( pixel[0] << (7 - xx) ) fileOut.write("0x%02X, " % byte) gimp.progress_update(float(y) / (height)) fileOut.write( "\n" ) fileOut.write("};\n" ) fileOut.write("#endif /* %s */\n" % filename.upper() ) gimp.progress_update(1) fileOut.close()
def load_mib2(filename, raw_filename): scrImg = pdb.file_png_load(filename, raw_filename) wh = scrImg.width ht = scrImg.height srcLayer = scrImg.layers[0] srcRgn = srcLayer.get_pixel_rgn(0, 0, wh, ht, False, False) sp_size = len(srcRgn[0, 0]) src_pixels = array("B", srcRgn[0:wh, 0:ht]) sp_size = 2 # GRAYA dp_size = 3 # RGB dest_pixels = array("B", "\x00" * (wh * ht * dp_size)) gimp.progress_init("Updating image") for i in xrange(0, wh): for j in xrange(0, ht): src_pos = (i + wh * j) * sp_size dest_pos = (i + wh * j) * dp_size i2 = (i / 2) * 2 src_pos2 = (i2 + wh * j) * sp_size srcPixel1 = src_pixels[src_pos:src_pos + sp_size] g = srcPixel1[1] gb = src_pixels[src_pos2:src_pos2 + sp_size][0] gr = src_pixels[src_pos2 + sp_size:src_pos2 + sp_size + sp_size][0] b = max(min(g - 512 + (gr * 4 + gb * 8) / 3, 255), 0) r = max(min(g - 512 + (gb * 4 + gr * 8) / 3, 255), 0) pixel = array("B", [r, g, b]) dest_pixels[dest_pos:dest_pos + dp_size] = pixel gimp.progress_update(float(i) / float(wh)) dstImg = gimp.pdb.gimp_image_new(wh, ht, RGB) dstLayer = pdb.gimp_layer_new(dstImg, wh, ht, RGB_IMAGE, "background", 100.0, NORMAL_MODE) dstImg.add_layer(dstLayer, 0) dstRgn = dstLayer.get_pixel_rgn(0, 0, wh, ht, True, False) dstRgn[0:wh, 0:ht] = dest_pixels.tostring() return dstImg
def python_ndsexport_A3I5(img, drawable, filename, raw_filename): pdb.gimp_layer_resize_to_image_size(drawable) width = drawable.width height = drawable.height fileOut = open(filename, "wb") ## TODO : Use pixelregion instead of gimp_drawable_get_pixel #pr = drawable.get_pixel_rgn(0, 0, width, height, False, False) gimp.progress_init(_("Saving as Nintendo DS A3I5")) imageIndex, indexedDrawable = index_copy_of_image(img, 16) fileOut.write("a3i5") # file header fileOut.write(struct.pack("<II", width, height)) for y in range(0, height): for x in range(0, width): (channels, pixel) = pdb.gimp_drawable_get_pixel(drawable, x, y) # TO OPTIMIZE, very slow if channels < 4: alpha = 7 else: alpha = round((pixel[3] / 255) * 7) (channels, pixel) = pdb.gimp_drawable_get_pixel(indexedDrawable, x, y) # TO OPTIMIZE, very slow index = pixel[0] value = int(alpha) << 5 value += index fileOut.write(struct.pack("<B", value)) gimp.progress_update( float((x + y * width) * 0.8) / (width * height)) createPalette(imageIndex, 32, fileOut) gimp.progress_update(1) fileOut.close() gimp.delete(img)
def load_wavefile(filename, raw_filename): gimp.progress_init("Importing Wavefile ...") progress = 0.0 progress_offset = 0.05 # Read the file. buf = Buffer(filename) buf -= buf.getMean() buf.normalize() n_pixels = buf.getLength() # Read ID3v1 tag if available. t = ID3v1Tag() w = None h = None if t.read(filename, False) and t.title == "GIMP+Python+Nsound": try: temp = re.search("w=[0-9]+", t.comment).group(0) w = int(temp[2:]) temp = re.search("h=[0-9]+", t.comment).group(0) h = int(temp[2:]) except: w = None h = None # If we didn't read the tag, create some dimensions that are 4:3 if w == None: ratio = 4.0 / 3.0 w = 4.0 h = 3.0 while w * h < n_pixels: r = w / h if r < ratio: w += 1.0 else: h += 1.0 if w >= 1600: break w = int(w) h = int(h) gimp.progress_update(progress_offset) img = gimp.Image(w, h, gimpfu.GRAY) layer = gimp.Layer(img, "Wavefile", w, h, gimpfu.GRAYA_IMAGE, 100.0, gimpfu.NORMAL_MODE) layer.fill(gimpfu.TRANSPARENT_FILL) img.add_layer(layer, 0) # New mask mask = layer.create_mask(0) layer.add_mask(mask) (X, Y) = (layer.width, layer.height) progress_step = (1.0 - progress_offset) / float(Y) k = 0 for y in range(Y): gimp.progress_update(progress_offset + float(y) / float(Y)) # Allocate memory pixels = Buffer(Y) for x in range(X): pixels << 127.0 * buf[k] + 127.0 k += 1 if k >= n_pixels: while x < X: pixels << 127.0 x += 1 break setRow(layer, y, [pixels]) if k >= n_pixels: break gimp.progress_update(1.0) # Apply changes layer.remove_mask(gimpfu.MASK_APPLY) return img
def LBP(self): width = self.drawable.width height = self.drawable.height #bpp = self.drawable.bpp rad = self.radius #debugging messages #print("Velikost obrazku: " + str(width) + "x" + str(height)) #create new output layer self.layer = gimp.Layer(self.image, "LBP", width, height, GRAY_IMAGE, 100, NORMAL_MODE) #add layer into image self.image.add_layer(self.layer, 0) #region for output dest_rgn = self.layer.get_pixel_rgn(0, 0, width, height, True, True) #custom array for results drawTo = array.array("B") #get image data (region) and convert to array imageArr = self.drawable.get_pixel_rgn(0, 0, width, height, False, False) imageArr_pixels = array.array("B", imageArr[0:width, 0:height]) #convert 1D array to 2D array tmp = np.reshape(imageArr_pixels, (-1, width)) #create array with mirrored border dataBorder = np.pad(array=tmp, pad_width=rad, mode='symmetric') gimp.progress_init("LBP") for x in range(rad, height + rad): for y in range(rad, width + rad): binaryNum = [] #get exactly eight pixels in radius from pixel [x,y] src_pixels = dataBorder[x - rad:x + 1 + rad:rad, y - rad:y + 1 + rad:rad] src_pixels = src_pixels.ravel() #make 2D array 1D #get value of the center pixel [x,y] center = src_pixels[4] #sequence of indexes indexesNeeded = [0, 1, 2, 5, 8, 7, 6, 3] for i in indexesNeeded: if src_pixels[i] > center: binaryNum.append(0) else: binaryNum.append(1) #"count" LBP for pixel st = ''.join(format(str(x)) for x in binaryNum) res = int(st, 2) drawTo.append(res) gimp.progress_update(float(x + 1) / height) #result dest_rgn[0:width, 0:height] = drawTo.tostring() #apply changes self.layer.flush() #apply selection mask self.layer.merge_shadow(True) #refresh self.layer.update(0, 0, width, height) #refresh gimp.displays_flush()
def initialize(self, message=None): gimp.progress_init(message if message is not None else "")
def hello(): """Mostra a mensagem Olá Mundo! na barra de progresso""" gimp.progress_init("Olá Mundo") for i in range(100): gimp.progress_update(i / 100.) time.sleep(.25)
def colorxhtml(img, drawable, filename, raw_filename, source_type, characters, size, separate): width = drawable.width height = drawable.height bpp = drawable.bpp if not drawable.is_rgb or drawable.has_alpha: return if source_type not in all_source_types: return gimp.tile_cache_ntiles(width / gimp.tile_width() + 1) html = file(filename, 'w') if separate: dirname, cssfile = os.path.split(filename) cssfile = os.path.splitext(cssfile)[0] + '.css' cssname = os.path.join(dirname, cssfile) css = file(cssname, 'w') if source_type == CHARS_SOURCE: chars = file(inspect.getsourcefile(colorxhtml)).read() elif source_type == CHARS_FILE: chars = file(characters).read() elif source_type == CHARS_PARAMETER: chars = characters allchars = string.maketrans('', '') goodchars = string.digits + string.ascii_letters + string.punctuation badchars = ''.join(c for c in allchars if c not in goodchars) chars = chars.translate(allchars, badchars) data = [escape_table.get(c, c) for c in chars] if data: data.reverse() else: data = list('X' * 80) pr = drawable.get_pixel_rgn(0, 0, width, height, False, False) gimp.progress_init(_("Saving as colored XHTML")) style = style_def % size if separate: ss = '<link rel="stylesheet" type="text/css" href="%s" />' % cssfile css.write(style) else: ss = '<style type="text/css">\n%s</style>' % style html.write(preamble % ss) colors = {} chars = [] for y in range(0, height): row = pr[0:width, y] while len(chars) < width: chars[0:0] = data for pixel in RowIterator(row, bpp): color = '%02x%02x%02x' % pixel style = 'background-color:black; color:#%s;' % color char = chars.pop() if separate: if color not in colors: css.write('span.N%s { %s }\n' % (color, style)) colors[color] = 1 html.write('<span class="N%s">%s</span>' % (color, char)) else: html.write('<span style="%s">%s</span>' % (style, char)) html.write('\n') gimp.progress_update(y / float(height)) html.write(postamble) html.close() if separate: css.close()
def remap_hue(self): #input can be RGB or RGBA bpp = self.drawable.bpp (bx1, by1, bx2, by2) = self.drawable.mask_bounds bw = bx2 - bx1 bh = by2 - by1 #input layer offset (ox, oy) = self.drawable.offsets src_rgn = self.drawable.get_pixel_rgn(bx1, by1, bw, bh, False, False) #all the input pixels in one huge array #src_rgn[...] returns a packed byte array as a string #we unpack this string using python array src_pixels = array.array("B", src_rgn[bx1:bx2, by1:by2]) #delete existing preview layer self.layer_destroy() #create new output layer self.layer = gimp.Layer(self.image, "Hue map", bw, bh, RGBA_IMAGE, 100, NORMAL_MODE) #set correct position self.layer.set_offsets(bx1 + ox, by1 + oy) dest_rgn = self.layer.get_pixel_rgn(0, 0, bw, bh, True, True) #all the output pixels dest_pixels = array.array("B", dest_rgn[0:bw, 0:bh]) #output is always RGBA dest_bpp = 4 #add layer into image self.image.add_layer(self.layer, 0) #for 8bit RGB, the hue resolution is 6*256 = 1536 #sampling in lower resolution (like 360°) would result in color loss #we pre-sample the gradient instead of sampling it on each pixel #it results in better performance on larger selections (> 39x39 px) num_samples = 6 * 256 hue_samples = pdb.gimp_gradient_get_uniform_samples( self.gradient_button.get_gradient(), num_samples + 1, False)[1] hues = [None] * num_samples for i in range(0, num_samples): #convert rgb into hue sample_rgb = gimpcolor.RGB(hue_samples[i * 4 + 0], hue_samples[i * 4 + 1], hue_samples[i * 4 + 2], hue_samples[i * 4 + 3]) hues[i] = sample_rgb.to_hsv().h #start a progress bar gimp.progress_init("Hue map") for y in range(0, bh): for x in range(0, bw): pos = (x + bw * y) * bpp #read a pixel as a 3 or 4 byte array c_array = src_pixels[pos:(pos + bpp)] #create a RGB struct, if there is no alpha, set it to 100% c_rgb = gimpcolor.RGB(c_array[0], c_array[1], c_array[2], c_array[3] if bpp == 4 else 255) #RGB -> HSV c_hsv = c_rgb.to_hsv() #calculate index into hue replacement array hue_index = int(round(c_hsv.h * num_samples)) #replace hue c_hsv.h = hues[hue_index] #HSV -> RGB c_rgb = c_hsv.to_rgb() #RGB -> byte array c_array[0:dest_bpp] = array.array("B", c_rgb[0:dest_bpp]) dest_pos = (x + bw * y) * dest_bpp #write a pixel into the output array dest_pixels[dest_pos:(dest_pos + dest_bpp)] = c_array #update the progress bar gimp.progress_update(float(y + 1) / bh) #write the output pixel array into the output layer dest_rgn[0:bw, 0:bh] = dest_pixels.tostring() #apply changes self.layer.flush() #apply selection mask self.layer.merge_shadow(True) #refresh self.layer.update(0, 0, bw, bh) #refresh gimp.displays_flush()
def run(img, layer, name, hi_lo, ftype, order, frequency, direction): gimp.context_push() img.undo_group_start() is_iir = None if ftype == "IIR": is_iir = True else: is_iir = False if img.base_type == gimpfu.RGB: type = gimpfu.RGBA_IMAGE else: type = gimpfu.GRAY_IMAGE new_layer = gimp.Layer(img, name, layer.width, layer.height, type, 100.0, gimpfu.NORMAL_MODE) new_layer.set_offsets(layer.offsets[0], layer.offsets[1]) new_layer.fill(gimpfu.TRANSPARENT_FILL) img.add_layer(new_layer, 0) # New mask mask = new_layer.create_mask(0) new_layer.add_mask(mask) f = None sample_rate = float(layer.width) if is_iir: if hi_lo == "LP": f = FilterLowPassIIR(sample_rate, order, frequency, 0.0) else: f = FilterHighPassIIR(sample_rate, order, frequency, 0.0) # Estimate filter delay pulse = Buffer(2 * order) pulse << 1.0 for i in range(0, order): pulse << 0.0 result = Buffer(2 * order) result << f.filter(pulse) # Find the peak mmax = result.getMax() delay = None for i in range(0, result.getLength()): if result[i] == mmax: delay = i + 1 break else: if hi_lo == "LP": f = FilterLowPassFIR(sample_rate, order, frequency) else: f = FilterHighPassFIR(sample_rate, order, frequency) delay = (f.getKernelSize() - 1) / 2 gimp.progress_init("Filtering pixels ...") done_factor = 1.0 offset = 0.0 directions = [direction] if direction == "Both": done_factor = 0.5 directions = ["X", "Y"] for axis in directions: if "X" == axis: (X, Y) = (layer.width, layer.height) else: (Y, X) = (layer.width, layer.height) for y in range(0, Y): gimp.progress_update(offset + done_factor * float(y) / float(Y)) pixels = getRow(layer, y, axis) for i in range(len(pixels)): buf = pixels[i] f.reset() # Prime the filter for j in range(delay): f.filter(buf[0]) last = buf[-1] k = 0 for j in range(buf.getLength()): # while j is < delay, throw out samples if j < delay: f.filter(buf[j]) else: buf[k] = f.filter(buf[j]) k += 1 for j in range(delay): buf[k] = f.filter(last) k += 1 pixels[i] = buf setRow(new_layer, y, pixels, axis) offset += 0.5 layer = new_layer gimp.progress_update(1.0) # Apply changes new_layer.remove_mask(gimpfu.MASK_APPLY) img.undo_group_end() gimp.context_pop()
def colorxhtml(img, drawable, filename, raw_filename, source_type, characters, size, separate): width = drawable.width height = drawable.height bpp = drawable.bpp if not drawable.is_rgb or drawable.has_alpha: return if source_type not in all_source_types: return gimp.tile_cache_ntiles(width / gimp.tile_width() + 1) html = file(filename, 'w') if separate: dirname, cssfile = os.path.split(filename) cssfile = os.path.splitext(cssfile)[0] + '.css' cssname = os.path.join(dirname, cssfile) css = file(cssname, 'w') if source_type == CHARS_SOURCE: chars = file(inspect.getsourcefile(colorxhtml)).read() elif source_type == CHARS_FILE: chars = file(characters).read() elif source_type == CHARS_PARAMETER: chars = characters allchars = string.maketrans('', '') goodchars = string.digits + string.ascii_letters + string.punctuation badchars = ''.join([c for c in allchars if c not in goodchars]) chars = chars.translate(allchars, badchars) data = [] for c in chars: data.append(escape_table.get(c, c)) if data: data.reverse() else: data = list('X' * 80) pr = drawable.get_pixel_rgn(0, 0, width, height, False, False) gimp.progress_init(_("Saving as colored XHTML")) style = style_def % size if separate: ss = '<link rel="stylesheet" type="text/css" href="%s" />' % cssfile css.write(style) else: ss = '<style type="text/css">\n%s</style>' % style html.write(preamble % ss) colors = {} chars = [] for y in range(0, height): row = pr[0:width, y] while len(chars) < width: chars[0:0] = data for pixel in RowIterator(row, bpp): color = '%02x%02x%02x' % pixel style = 'background-color:black; color:#%s;' % color char = chars.pop() if separate: if color not in colors: css.write('span.N%s { %s }\n' % (color, style)) colors[color] = 1 html.write('<span class="N%s">%s</span>' % (color, char)) else: html.write('<span style="%s">%s</span>' % (style, char)) html.write('\n') gimp.progress_update(y / float(height)) html.write(postamble) html.close() if separate: css.close()
def makebuttons(self, filename = None, outdir = None, font = None, strcolor = None, transparency = False, bgcolor = None, glow = False, glowcolor = None, usepattern = False, pattern = None, buttoncolor = None, roundradius = None, padding = None, glowsize = None, bevelwidth = None, nova = False, novasparkles = None, novaradius = None, novacolor = None, writexcf = False, makeinactive = True, makeactive = True, makepressed = True, makejscript = True): # import used gimp pdb functions createtext = pdb['gimp_text_fontname'] selectionlayeralpha = pdb['gimp_selection_layer_alpha'] selectionfeather = pdb['gimp_selection_feather'] bucketfill = pdb['gimp_edit_bucket_fill'] selectionall = pdb['gimp_selection_all'] editclear = pdb['gimp_edit_clear'] rectselect = pdb['gimp_rect_select'] ellipseselect = pdb['gimp_ellipse_select'] selectionshrink = pdb['gimp_selection_shrink'] selectionnone = pdb['gimp_selection_none'] fill = pdb['gimp_edit_fill'] bumpmap = pdb['plug_in_bump_map'] novaplugin = pdb['plug_in_nova'] xcfsave = pdb['gimp_xcf_save'] gimp.progress_init() stringfile = open(filename) strings = [line.strip() for line in stringfile.readlines() if self.toprocess(line)] stringfile.close() t2nm = text_to_name_mapper(strings) (fontname, fontsize) = self.parsefont(font) (maxx, maxy) = self.getmaxextents(strings, fontsize, fontname) logging.debug("fontname: %s, fontsize: %d, maxx: %d, maxy: %d", fontname, int(fontsize), maxx, maxy) width = maxx + (padding*4) height = maxy + (padding*4) logging.debug("width: %d, height: %d", width, height) if roundradius > height/2: roundradius = height/2 - 1 if roundradius > width/2: roundradius = width/2 - 1 logging.debug("roundradius: %d", roundradius) for text in strings: image = gimp.Image(width, height, RGB) image.disable_undo() gimp.set_foreground(strcolor) textlayer = createtext(image, None, padding*2, padding*2, text, 0, 1, fontsize, 1, fontname) # center the text textlayer.set_offsets((image.width - textlayer.width)/2 - 1, (image.height - textlayer.height)/2 - 1) textlayer.lock_alpha = True textlayer.name = text if glow: texteffect = textlayer.copy(True) image.add_layer(texteffect, len(image.layers)) offs = texteffect.offsets texteffect.resize(image.width, image.height, offs[0], offs[1]) texteffect.lock_alpha = False image.active_layer = texteffect selectionlayeralpha(texteffect) selectionfeather(image, glowsize) gimp.set_foreground(glowcolor) bucketfill(texteffect, FG_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) btnlayer0 = gimp.Layer(image, "Background", width, height, RGBA_IMAGE, 100, NORMAL_MODE) image.add_layer(btnlayer0, len(image.layers)) selectionall(image) editclear(btnlayer0) offs = btnlayer0.offsets rectselect(image, offs[0] + roundradius, offs[1], btnlayer0.width - roundradius*2, btnlayer0.height, CHANNEL_OP_REPLACE, 0, 0) rectselect(image, offs[0], offs[1] + roundradius, btnlayer0.width, btnlayer0.height - roundradius*2, CHANNEL_OP_ADD, 0, 0) ellipseselect(image, offs[0], offs[1], roundradius*2, roundradius*2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0] + btnlayer0.width - roundradius*2, offs[1], roundradius*2, roundradius*2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0], offs[1] + btnlayer0.height - roundradius*2, roundradius*2, roundradius*2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0] + btnlayer0.width - roundradius*2, offs[1] + btnlayer0.height - roundradius*2, roundradius*2, roundradius*2, CHANNEL_OP_ADD, False, 0, 0) selectionshrink(image, 1) selectionfeather(image, 2) if usepattern: pdb['gimp_context_set_pattern'](pattern) bucketfill(btnlayer0, PATTERN_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) else: gimp.set_background(buttoncolor) bucketfill(btnlayer0, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) selectionnone(image) selectionlayeralpha(btnlayer0) selectionfeather(image, 2) bumplayer = gimp.Layer(image, "Bumpmap", width, height, RGBA_IMAGE, 100, NORMAL_MODE) gimp.set_background(0, 0, 0) image.add_layer(bumplayer, 0) fill(bumplayer, BACKGROUND_FILL) for index in range(1, bevelwidth -1): greyness = index*255/bevelwidth; gimp.set_background(greyness, greyness, greyness) bucketfill(bumplayer, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionshrink(image, 1) gimp.set_background(255, 255, 255) bucketfill(bumplayer, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionnone(image) btnlayer1 = btnlayer0.copy(True) btnlayer2 = btnlayer0.copy(True) image.add_layer(btnlayer1, len(image.layers)) image.add_layer(btnlayer2, len(image.layers)) bumpmap(image, btnlayer1, bumplayer, 125, 45, 3, 0, 0, 0, 0, 0, 0, 1) bumpmap(image, btnlayer2, bumplayer, 125, 45, 3, 0, 0, 0, 0, 0, 1, 1) image.remove_layer(bumplayer) #gimp.delete(bumplayer) if nova: novalayer = gimp.Layer(image, "Nova", width, height, RGBA_IMAGE, 75, NORMAL_MODE) image.add_layer(novalayer, 0) selectionall(image) image.active_layer = novalayer editclear(novalayer) selectionnone(image) novaplugin(image, novalayer, width/4, height/4, novacolor, novaradius, novasparkles, 0) blackboard = gimp.Layer(image, "Blackboard", width, height, RGBA_IMAGE, 100, NORMAL_MODE) image.add_layer(blackboard, len(image.layers)) selectionall(image) if transparency: blackboard.lock_alpha = True editclear(blackboard) else: gimp.set_background(bgcolor) bucketfill(blackboard, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionnone(image) if writexcf: fname = t2nm.asfilename(text, 'xcf', dirname = outdir) xcfsave(0, image, textlayer, fname, fname) if makepressed: btnlayer0.visible = False btnlayer1.visible = False btnlayer2.visible = True if nova: novalayer.visible = True self.saveaspng(t2nm.asfilename(text, 'png', 'p_', outdir), image, transparency) if makeactive: btnlayer0.visible = False btnlayer1.visible = True btnlayer2.visible = False if nova: novalayer.visible = True self.saveaspng(t2nm.asfilename(text, 'png', 'a_', outdir), image, transparency) if makeinactive: btnlayer0.visible = True btnlayer1.visible = False btnlayer2.visible = False if nova: novalayer.visible = False self.saveaspng(t2nm.asfilename(text, 'png', 'i_', outdir), image, transparency) image.enable_undo() #gimp.Display(image) gimp.progress_update((strings.index(text)+1)/len(strings)) gimp.delete(image) if makejscript: self.writejs(outdir, strings, width, height, t2nm) self.writecss(outdir, bgcolor) self.writehtml(outdir, strings, width, height, t2nm)
def do_stuff(img, layer, mapswide, mapstall) : setup_palette() gimp.progress_init("Minecraft Mapifying " + layer.name + "...") # Disable Undo as we are creating a new window pdb.gimp_image_undo_disable(img) new_img = pdb.gimp_image_duplicate(img) gimp.Display(new_img) gimp.displays_flush() pdb.gimp_image_undo_disable(new_img) # Calculate the height and width of the new image img_ratio = float(layer.width) / float(layer.height) map_ratio = float(mapswide) / float(mapstall) offset_x = 0 offset_y = 0 width = 0 height = 0 # If the aspect ratio of the original image is greater than the aspect ratio of the maps, # then the original image needs padding above and below to fit the maps if img_ratio > map_ratio: width = mapswide * 128 height = int(float(width) / img_ratio) offset_y = ((map_ratio * 128) - height) / 2 # otherwise padding is needed to the left and right else: height = mapstall * 128 width = int(img_ratio * float(height)) offset_x = ((map_ratio * 128) - width) / 2 # Resize the image to the fit the maps requested pdb.gimp_context_set_interpolation(INTERPOLATION_CUBIC) pdb.gimp_image_scale(new_img, width, height) new_img.resize(mapswide * 128, mapstall * 128, int(offset_x), int(offset_y)) # Create a new background layer, fill it with the background color, and flatten the image to create the padding new_img.add_layer(new_img.active_layer.copy(), 1) new_img.layers[1].resize(mapswide * 128, mapstall * 128, int(offset_x), int(offset_y)) new_img.layers[1].fill(BACKGROUND_FILL) new_img.flatten() new_img.active_layer.name = layer.name # Turn the image into the map palette pdb.gimp_image_convert_indexed(new_img, CONVERT_DITHER_FS_LOWBLEED, CONVERT_PALETTE_CUSTOM, 0, False, True, "Minecraft Map In Order") gimp.displays_flush() # Create 2 duplicate layers as they will be used in outputing the build details new_img.add_layer(new_img.layers[0].copy(), 1) new_img.add_layer(new_img.layers[0].copy(), 2) new_img.layers[0].name = layer.name + " [Map]" new_img.layers[1].name = layer.name + " [Types]" new_img.layers[2].name = layer.name + " [Heights]" scan_image(new_img.layers[0], new_img.layers[1], new_img.layers[2]) # Enable undo again pdb.gimp_image_undo_enable(img) pdb.gimp_image_undo_enable(new_img)
def run(img, layer, name, domain, axis): if axis == "X": (X, Y) = (layer.width, layer.height) else: (Y, X) = (layer.width, layer.height) mag_layer = None pha_layer = None type = None new_layers = [] gimp.context_push() img.undo_group_start() if img.base_type == gimpfu.RGB: type = gimpfu.RGBA_IMAGE else: type = gimpfu.GRAY_IMAGE if domain == "FORWARD": w = X X = FFTransform.roundUp2(X) new_layers.append( gimp.Layer(img, name + " Phase %d" % w, X/2, Y, type, 100.0, gimpfu.NORMAL_MODE)) new_layers.append( gimp.Layer(img, name + " Magnitude %d" % w, X/2, Y, type, 100.0, gimpfu.NORMAL_MODE)) elif domain == "REVERSE": # Search the image for the highest layers that are labeled with Phase # and Magnitude for l in img.layers: if " Magnitude " in l.name: mag_layer = l elif " Phase " in l.name: pha_layer = l if mag_layer != None and pha_layer != None: break if mag_layer == None: raise Exception("Could not locate 'FFT Magnitude X' layer!") elif pha_layer == None: raise Exception("Could not locate 'FFT Phase X' layer!") # Okay, we have both layers, read the width in the name X = None t1 = re.search(" [0-9]+", mag_layer.name).group(0) t2 = re.search(" [0-9]+", pha_layer.name).group(0) if t1 == t2: X = int(t1) if X == None: raise Exception("Could not determing layer's original size!") new_layers.append( gimp.Layer(img, name + " Reverse", X, Y, type, 100.0, gimpfu.NORMAL_MODE)) for i in range (len(new_layers)): new_layers[i].set_offsets(layer.offsets[0],layer.offsets[1]) new_layers[i].fill(gimpfu.TRANSPARENT_FILL) img.add_layer(new_layers[i], 0) # New mask mask = new_layers[i].create_mask(0) new_layers[i].add_mask(mask) gimp.progress_init("Transforming pixels ...") transform = FFTransform(X) if domain == "FORWARD": for y in range(Y): gimp.progress_update(float(y) / float(Y)) pixels = getRow(layer, y, axis) output_pixels = [ [], [] ] for color in range(len(pixels)): buf = pixels[color] buf.normalize() # Transform into frequency domain if domain == "FORWARD": # Perform over sampled FFT fdomain = transform.fft(buf, X, 0) mag = fdomain[0].getMagnitude() pha = fdomain[0].getPhase() mag.normalize() pha.normalize() # Scale to pixel max mag *= 255.0 pha *= 255.0 # Stuff into the output pixels output_pixels[0].append(pha) output_pixels[1].append(mag) for i in range(len(output_pixels)): setRow(new_layers[i], y, output_pixels[i], axis) elif domain == "REVERSE": for y in range(Y): gimp.progress_update(float(y) / float(Y)) pixels = {} pixels["mag"] = getRow(mag_layer, y, axis) pixels["pha"] = getRow(pha_layer, y, axis) output_pixels = [] for color in range(len(pixels["mag"])): mag = pixels["mag"][color] pha = pixels["pha"][color] mag.normalize() # Center the phase about 0.0 and scale by PI pha -= 0.5 * pha.getMean() pha.normalize() pha *= math.pi ch = FFTChunk(X) ch.setPolar(mag,pha) tdomain = transform.ifft([ch]) tdomain.normalize() output_pixels.append(255.0 * tdomain) setRow(new_layers[0], y, output_pixels, axis) gimp.progress_update(1.0) # Apply changes for i in range(len(new_layers)): new_layers[i].remove_mask(gimpfu.MASK_APPLY) img.undo_group_end() gimp.context_pop()
def makebuttons(self, filename=None, outdir=None, font=None, strcolor=None, transparency=False, bgcolor=None, glow=False, glowcolor=None, usepattern=False, pattern=None, buttoncolor=None, roundradius=None, padding=None, glowsize=None, bevelwidth=None, nova=False, novasparkles=None, novaradius=None, novacolor=None, writexcf=False, makeinactive=True, makeactive=True, makepressed=True, makejscript=True): # import used gimp pdb functions createtext = pdb['gimp_text_fontname'] selectionlayeralpha = pdb['gimp_selection_layer_alpha'] selectionfeather = pdb['gimp_selection_feather'] bucketfill = pdb['gimp_edit_bucket_fill'] selectionall = pdb['gimp_selection_all'] editclear = pdb['gimp_edit_clear'] rectselect = pdb['gimp_rect_select'] ellipseselect = pdb['gimp_ellipse_select'] selectionshrink = pdb['gimp_selection_shrink'] selectionnone = pdb['gimp_selection_none'] fill = pdb['gimp_edit_fill'] bumpmap = pdb['plug_in_bump_map'] novaplugin = pdb['plug_in_nova'] xcfsave = pdb['gimp_xcf_save'] gimp.progress_init() stringfile = open(filename) strings = [ line.strip() for line in stringfile.readlines() if self.toprocess(line) ] stringfile.close() t2nm = text_to_name_mapper(strings) (fontname, fontsize) = self.parsefont(font) (maxx, maxy) = self.getmaxextents(strings, fontsize, fontname) logging.debug("fontname: %s, fontsize: %d, maxx: %d, maxy: %d", fontname, int(fontsize), maxx, maxy) width = maxx + (padding * 4) height = maxy + (padding * 4) logging.debug("width: %d, height: %d", width, height) if roundradius > height / 2: roundradius = height / 2 - 1 if roundradius > width / 2: roundradius = width / 2 - 1 logging.debug("roundradius: %d", roundradius) for text in strings: image = gimp.Image(width, height, RGB) image.disable_undo() gimp.set_foreground(strcolor) textlayer = createtext(image, None, padding * 2, padding * 2, text, 0, 1, fontsize, 1, fontname) # center the text textlayer.set_offsets((image.width - textlayer.width) / 2 - 1, (image.height - textlayer.height) / 2 - 1) textlayer.lock_alpha = True textlayer.name = text if glow: texteffect = textlayer.copy(True) image.add_layer(texteffect, len(image.layers)) offs = texteffect.offsets texteffect.resize(image.width, image.height, offs[0], offs[1]) texteffect.lock_alpha = False image.active_layer = texteffect selectionlayeralpha(texteffect) selectionfeather(image, glowsize) gimp.set_foreground(glowcolor) bucketfill(texteffect, FG_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) btnlayer0 = gimp.Layer(image, "Background", width, height, RGBA_IMAGE, 100, NORMAL_MODE) image.add_layer(btnlayer0, len(image.layers)) selectionall(image) editclear(btnlayer0) offs = btnlayer0.offsets rectselect(image, offs[0] + roundradius, offs[1], btnlayer0.width - roundradius * 2, btnlayer0.height, CHANNEL_OP_REPLACE, 0, 0) rectselect(image, offs[0], offs[1] + roundradius, btnlayer0.width, btnlayer0.height - roundradius * 2, CHANNEL_OP_ADD, 0, 0) ellipseselect(image, offs[0], offs[1], roundradius * 2, roundradius * 2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0] + btnlayer0.width - roundradius * 2, offs[1], roundradius * 2, roundradius * 2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0], offs[1] + btnlayer0.height - roundradius * 2, roundradius * 2, roundradius * 2, CHANNEL_OP_ADD, False, 0, 0) ellipseselect(image, offs[0] + btnlayer0.width - roundradius * 2, offs[1] + btnlayer0.height - roundradius * 2, roundradius * 2, roundradius * 2, CHANNEL_OP_ADD, False, 0, 0) selectionshrink(image, 1) selectionfeather(image, 2) if usepattern: pdb['gimp_context_set_pattern'](pattern) bucketfill(btnlayer0, PATTERN_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) else: gimp.set_background(buttoncolor) bucketfill(btnlayer0, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, True, 0, 0) selectionnone(image) selectionlayeralpha(btnlayer0) selectionfeather(image, 2) bumplayer = gimp.Layer(image, "Bumpmap", width, height, RGBA_IMAGE, 100, NORMAL_MODE) gimp.set_background(0, 0, 0) image.add_layer(bumplayer, 0) fill(bumplayer, BACKGROUND_FILL) for index in range(1, bevelwidth - 1): greyness = index * 255 / bevelwidth gimp.set_background(greyness, greyness, greyness) bucketfill(bumplayer, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionshrink(image, 1) gimp.set_background(255, 255, 255) bucketfill(bumplayer, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionnone(image) btnlayer1 = btnlayer0.copy(True) btnlayer2 = btnlayer0.copy(True) image.add_layer(btnlayer1, len(image.layers)) image.add_layer(btnlayer2, len(image.layers)) bumpmap(image, btnlayer1, bumplayer, 125, 45, 3, 0, 0, 0, 0, 0, 0, 1) bumpmap(image, btnlayer2, bumplayer, 125, 45, 3, 0, 0, 0, 0, 0, 1, 1) image.remove_layer(bumplayer) #gimp.delete(bumplayer) if nova: novalayer = gimp.Layer(image, "Nova", width, height, RGBA_IMAGE, 75, NORMAL_MODE) image.add_layer(novalayer, 0) selectionall(image) image.active_layer = novalayer editclear(novalayer) selectionnone(image) novaplugin(image, novalayer, width / 4, height / 4, novacolor, novaradius, novasparkles, 0) blackboard = gimp.Layer(image, "Blackboard", width, height, RGBA_IMAGE, 100, NORMAL_MODE) image.add_layer(blackboard, len(image.layers)) selectionall(image) if transparency: blackboard.lock_alpha = True editclear(blackboard) else: gimp.set_background(bgcolor) bucketfill(blackboard, BG_BUCKET_FILL, NORMAL_MODE, 100, 0, False, 0, 0) selectionnone(image) if writexcf: fname = t2nm.asfilename(text, 'xcf', dirname=outdir) xcfsave(0, image, textlayer, fname, fname) if makepressed: btnlayer0.visible = False btnlayer1.visible = False btnlayer2.visible = True if nova: novalayer.visible = True self.saveaspng(t2nm.asfilename(text, 'png', 'p_', outdir), image, transparency) if makeactive: btnlayer0.visible = False btnlayer1.visible = True btnlayer2.visible = False if nova: novalayer.visible = True self.saveaspng(t2nm.asfilename(text, 'png', 'a_', outdir), image, transparency) if makeinactive: btnlayer0.visible = True btnlayer1.visible = False btnlayer2.visible = False if nova: novalayer.visible = False self.saveaspng(t2nm.asfilename(text, 'png', 'i_', outdir), image, transparency) image.enable_undo() #gimp.Display(image) gimp.progress_update((strings.index(text) + 1) / len(strings)) gimp.delete(image) if makejscript: self.writejs(outdir, strings, width, height, t2nm) self.writecss(outdir, bgcolor) self.writehtml(outdir, strings, width, height, t2nm)
def fileMIB2save(image, drawable, filename, raw_filename, dummy, limcolors, extlbl): # height = 480 # width = 800 lbl_height = 100 lbl_width = 480 lbl_rect = [160, 320, lbl_width + 160, lbl_height + 320] #if not ((image.width == width and image.height==height) or (image.width == lbl_width and image.height==lbl_height)): # raise ValueError('Invalid resolution. Allowed only 800x480 or 480x100') if (image.width % 2 != 0): raise ValueError('Invalid resolution. Width must be even.') height = image.height width = image.width extlbl = extlbl and (image.width == 800 and image.height == 480) #prepare source image img = pdb.gimp_image_duplicate(image) try: #reduce colors to limcolors to fit 1mb limit if (img.base_type != RGB): pdb.gimp_image_convert_rgb(img) srcLayer = img.flatten() if (limcolors > 0): pdb.gimp_drawable_posterize(srcLayer, limcolors) # # pdb.gimp_image_convert_indexed(img, NO_DITHER, MAKE_PALETTE, limcolors, False, True, "") # pdb.gimp_image_convert_rgb(img) #extract pixel array rgn = srcLayer.get_pixel_rgn(0, 0, width, height, False, False) sp_size = len(rgn[0, 0]) src_pixels = array("B", rgn[0:width, 0:height]) finally: pdb.gimp_image_delete(img) #prepare desination pixel array dp_size = 2 # GRAYA dest_pixels = array("B", "\x00" * (width * height * dp_size)) dest_pixels_label = array("B", "\x00" * (lbl_width * lbl_height * dp_size)) #start image converting gimp.progress_init("Updating image") for i in xrange(0, width): for j in xrange(0, height): src_pos = (i + width * j) * sp_size dest_pos = (i + width * j) * dp_size srcPixel = src_pixels[src_pos:src_pos + sp_size] r = srcPixel[0] g = srcPixel[1] b = srcPixel[2] if ((i % 2) == 0): r2 = src_pixels[src_pos + sp_size:src_pos + sp_size + sp_size][0] r = int(math.sqrt((r * r + r2 * r2) / 2)) px = (((b - r) / 2 + 128) + ((b - g) / 2 + 128)) / 2 else: b2 = src_pixels[src_pos - sp_size:src_pos][2] b = int(math.sqrt((b * b + b2 * b2) / 2)) px = (((r - b) / 2 + 128) + ((r - g) / 2 + 128)) / 2 pixel = array("B", [px, g]) if (extlbl and (i >= lbl_rect[0]) and (i < lbl_rect[2]) and (j >= lbl_rect[1]) and (j < lbl_rect[3])): lbl_dest_pos = (i - lbl_rect[0] + lbl_width * (j - lbl_rect[1])) * dp_size dest_pixels_label[lbl_dest_pos:lbl_dest_pos + dp_size] = pixel pixel = array("B", [128, 0]) dest_pixels[dest_pos:dest_pos + dp_size] = pixel gimp.progress_update(float(i) / float(width)) #save results to the file newImg = gimp.pdb.gimp_image_new(width, height, GRAY) newLayer = pdb.gimp_layer_new(newImg, width, height, 3, "background", 100.0, NORMAL_MODE) newImg.add_layer(newLayer, 0) dstRgn = newLayer.get_pixel_rgn(0, 0, width, height, True, False) dstRgn[0:width, 0:height] = dest_pixels.tostring() newLayer.flush() pdb.file_png_save(newImg, newLayer, filename, raw_filename, 0, 9, 0, 0, 0, 0, 0) #save label to the file if (extlbl): lblImg = gimp.pdb.gimp_image_new(lbl_width, lbl_height, GRAY) lblLayer = pdb.gimp_layer_new(lblImg, lbl_width, lbl_height, 3, "label", 100.0, NORMAL_MODE) lblImg.add_layer(lblLayer, 0) lblRgn = lblLayer.get_pixel_rgn(0, 0, lbl_width, lbl_height, True, False) lblRgn[0:lbl_width, 0:lbl_height] = dest_pixels_label.tostring() lblLayer.flush() fpath = os.path.split(filename) fname = os.path.splitext(fpath[1]) lbl_filename = os.path.join(fpath[0], fname[0] + "_lbl" + fname[1]) pdb.file_png_save(lblImg, lblLayer, lbl_filename, lbl_filename, 0, 9, 0, 0, 0, 0, 0)