def rgbColorFinder(rgbImg, colormin=(0, 0, 0), colormax=(255, 255, 255), allbands=1, rmode='1'): '''analyzes an RGB image, returns an image of the same size where each pixel is WHITE if the pixel in rgbImage MATCHES the color range colormin-to-colormax, or BLACK if the pixel in rgbImage DOES NOT MATCH the color range. a pixel is MATCHES the color range if allbands!=0 and if for EVERY color pixel[i], colormin[i]<=pixel[i] and pixel[i]<=colormax[i], or if allbands==0 and if for ANY color pixel[i], colormin[i]<=pixel[i] and pixel[i]<=colormax[i]. rmode determines the mode of the returned image ("1", "L" or "RGB") jjk 12/11/02''' inbands = rgbImg.split() outbands = [] for srcband, cmin, cmax in zip(inbands, colormin, colormax): outbands.append( srcband.point( lambda v1, v2=cmin, v3=cmax: v2 <= v1 and v1 <= v3 and 255)) if allbands == 0: tband = ImageChops.lighter( ImageChops.lighter(outbands[0], outbands[1]), outbands[2]) else: tband = ImageChops.darker(ImageChops.darker(outbands[0], outbands[1]), outbands[2]) if rmode == 'L': return tband elif rmode == 'RGB': return Image.merge('RGB', (tband, tband, tband)) # 'RGB' else: # rmode=='1' return tband.convert('1')
def color_grad_magnitude(image): red, green, blue = image.split() red_grad_mag = grad_magnitude(red) green_grad_mag = grad_magnitude(green) blue_grad_mag = grad_magnitude(blue) tmp_image = ImageChops.lighter(red_grad_mag, green_grad_mag) return ImageChops.lighter(tmp_image, blue_grad_mag)
def make(src_path, out_path): src = Image.open(src_path) src = src.copy() (srcr, srcg, srcb, srca) = src.split() white = ImageChops.constant(src, 255) outr = cast_gradation(srcr, 0, 90) outg = cast_gradation(srcg, 0, 90) outb = cast_gradation(srcb, 0, 90) outa = srca.copy() outr = ImageChops.composite(srcr, white, srca) outg = ImageChops.composite(srcg, white, srca) outb = ImageChops.composite(srcb, white, srca) (shadow_a, shadow) = make_inset_shadow(srca) outr = ImageChops.subtract(outr, shadow, 1, 0) outg = ImageChops.subtract(outg, shadow, 1, 0) outb = ImageChops.subtract(outb, shadow, 1, 0) outa = ImageChops.lighter(outa, shadow_a) (highlight_a, highlight) = make_highlight(srca) outa = ImageChops.lighter(outa, highlight) outa = ImageChops.subtract(outa, ImageChops.constant(outa, 25), 1, 0) out = Image.merge('RGBA', (outr, outg, outb, outa)) out.save(out_path)
def seg_mask(iseries, sbinfilepath, segmaskfilepath, segsbfilepath,origfilepath,expfilepath,segexpfilepath,segorigfilepath): #iseries is a filename, without jpg on the end and with sb on the end # First, apply mask to sb image - mask is black (or grey) on white background filename = re.sub('_mask','',iseries) + '.jpg' #this is the sb image # print 'Initial', filename maskim = Image.open(segmaskfilepath+ re.sub('.jpg','_mask.jpg',filename)).convert("L") # Mask not always black so first make sure it is threshold = 141 maskim = maskim.point(lambda p: p > threshold and 255) threshfilename = re.sub('_sb','_sbthres', filename) sbim = Image.open(sbinfilepath + threshfilename) try: # print 'Get thresh' seg_sb = ImageChops.lighter(sbim,maskim) seg_sb.save(segsbfilepath+ re.sub('.jpg','_seg.jpg',threshfilename) ) except IOError: print 'error in file' #Now open the original image - get rid of sb from filename filename = re.sub('_sb','', filename) origim = Image.open(origfilepath + filename).convert("L") seg_orig = ImageChops.lighter(origim,maskim) seg_orig.save(segorigfilepath+ re.sub('.jpg','_seg_orig.jpg',filename)) #Now open the exp image and apply mask # First make mask white on black maskim = ImageChops.invert(maskim) # Now extract all the pixels that are white and make this region a transparent region on the mask maskim = maskim.convert('LA') datas = maskim.getdata() newData = list() for item in datas: if item[0] == 255: newData.append((255, 0)) else: newData.append(item) maskim.putdata(newData) #img.save("img2.png", "PNG") l,a = maskim.split() # Check that exp file exists if os.path.exists(expfilepath + re.sub('ish','exp',filename)): #seg_exp = ImageChops.logical_and(expim,maskim) expim = Image.open(expfilepath + re.sub('ish','exp',filename)).convert("LA") # should be a grayscale image expim.paste(maskim, mask = a) expim = expim.convert("L") expim.save(segexpfilepath+ re.sub('.jpg','_seg_exp.tif',filename)) else: print 'N'
def generate_image(text, font_file, size, colour, image_destination): """ Text transform based on: http://nedbatchelder.com/blog/200801/truly_transparent_text_with_pil.html http://phark.typepad.com/phark/2003/08/accessible_imag.html """ pos = (0,0) image = Image.new("RGB", (1, 1), (0,0,0)) font = ImageFont.truetype(font_file, size) image = image.resize(font.getsize(text)) alpha = Image.new("L", image.size, "black") # Make a grayscale image of the font, white on black. imtext = Image.new("L", image.size, 0) drtext = ImageDraw.Draw(imtext) drtext.text(pos, text, font=font, fill="white") # Add the white text to our collected alpha channel. Gray pixels around # the edge of the text will eventually become partially transparent # pixels in the alpha channel. alpha = ImageChops.lighter(alpha, imtext) # Make a solid colour, and add it to the colour layer on every pixel # that has even a little bit of alpha showing. solidcolour = Image.new("RGBA", image.size, colour) immask = Image.eval(imtext, lambda p: 255 * (int(p != 0))) image = Image.composite(solidcolour, image, immask) # These two save()s are just to get demo images of the process. #image.save("transcolour.png", "PNG") #alpha.save("transalpha.png", "PNG") # Add the alpha channel to the image, and save it out. image.putalpha(alpha) image.save(image_destination, 'PNG') return image
def make_inset_shadow(alpha): mc = alpha.copy() for i in xrange(6): mc = mc.filter(ImageFilter.SMOOTH_MORE) mc = ImageChops.subtract(alpha, mc) mcb = ImageEnhance.Brightness(mc).enhance(0.35) m1 = alpha.copy() for i in xrange(6): m1 = m1.filter(ImageFilter.SMOOTH_MORE) m1 = m1.offset(0, OFFSET_S) m1 = ImageChops.subtract(alpha, m1) m1b = ImageEnhance.Brightness(m1).enhance(0.35) m = ImageChops.lighter(mc, m1) mb = ImageChops.lighter(mcb, m1b) return (m, mb)
def do_lighter(self): """usage: lighter <image:pic1> <image:pic2> Pop the two top images, push an image of the lighter pixels of both. """ import ImageChops image1 = self.do_pop() image2 = self.do_pop() self.push(ImageChops.lighter(image1, image2))
def ShowComposite(self, widget): if self.event_jpeg_file: os.kill(self.event_jpeg_file.pid, signal.SIGTERM) self.event_jpeg_file = None self.frame_index = 0 if self.timeout: gobject.source_remove(self.timeout) self.timeout = None if not self.current_path: return event_text_file = file(self.current_path, "r") if not event_text_file: return event_play_list = event_text_file.readlines() if not event_play_list: return event_text_file.close() self.raw_image = None for txt in event_play_list: path = self.ImagePath(txt) if not os.path.exists(path): return args = ["/usr/bin/djpeg", "-grayscale", "-pnm", path] event_jpeg_file = Popen(args, bufsize=-1, shell=False, stdout=PIPE) magic = event_jpeg_file.stdout.read(17) if magic != "P5\n640 14400\n255\n": os.kill(event_jpeg_file.pid, signal.SIGTERM) return for i in range(30): s = event_jpeg_file.stdout.read(640 * 480) img2 = Image.new("P", (640, 480)) img2.putdata(s) if self.raw_image == None: self.raw_image = img2 else: self.raw_image = ImageChops.lighter(self.raw_image, img2) event_jpeg_file.wait() if not self.gray_scale: self.raw_image.putpalette(self.palette) img = self.raw_image.convert("RGB") s = img.tostring() pixbuf = gtk.gdk.pixbuf_new_from_data(s, gtk.gdk.COLORSPACE_RGB, False, 8, 640, 480, 640 * 3) self.img.set_from_pixbuf(pixbuf)
def draw_text(self, text, position=(0, 0), color='black', font=None, font_size=12, rotation=0, **kwargs): """Draws a text on the base image.""" font = self.font(font_size) text_image = Image.new('L', self.dimensions, 'black') draw_text_image = ImageDraw.Draw(text_image) draw_text_image.text(position, text, font=font, fill='white') alpha = Image.new('L', self.dimensions) alpha = ImageChops.lighter(alpha, text_image) solidcolor = Image.new('RGBA', self.dimensions, color) image_mask = Image.eval(text_image, lambda p: 255 * (int(p != 0))) self.base_image = Image.composite(solidcolor, self.base_image, image_mask) self.base_image.putalpha(alpha)
def PILcomposite(baseim,stamp,x,y,comptype,mask=None): """ composite an image with another image, we assume that the stamp image is smaller than the base image, return value is the stamp put on the base image at the specified point. This function pays no attention to image locks. """ leftcorrection=0 rightcorrection=0 topcorrection=0 bottomcorrection=0 if x<0: leftcorrection=0-x if y<0: topcorrection=0-y if baseim.size[0]<x+stamp.size[0]: rightcorrection=x+stamp.size[0]-baseim.size[0] if baseim.size[1]<y+stamp.size[1]: bottomcorrection=y+stamp.size[1]-baseim.size[1] if leftcorrection or rightcorrection or topcorrection or bottomcorrection: stamp=stamp.crop((leftcorrection,rightcorrection,stamp.size[0]-rightcorrection,stamp.size[1]-leftcorrection)) baseswatch=baseim.crop((x,y,x+stamp.size[0],y+stamp.size[1])) if comptype==ImageCombineTypes.composite: newswatch=ImageChops.composite(baseswatch,stamp,None) elif comptype==ImageCombineTypes.lightest: newswatch=ImageChops.lighter(baseswatch,stamp) else: print "Unknown composite mode passed to PILcomposite" return #print "combined stamp:" #print printPILImage(stamp) #print "onto image:" #print printPILImage(baseswatch) #print "to produce:" #print printPILImage(newswatch) baseim.paste(newswatch,box=(x,y),mask=mask)
def _img_from_text(text, font, size=12, color='#000', decoration={}): """ Draws text with font, size, color and decoration parameters. Caches images and returns (html or object, width, size) of new or exists image """ image_path = path.join(settings.MEDIA_ROOT, HEADLINE_CACHE_DIR) font_path = path.join(settings.MEDIA_ROOT, HEADLINE_FONTS_DIR) id = "headline-%s" % md5(smart_str(''.join((text, font, size.__str__(), color, decoration.__str__())))).hexdigest() image_file = path.join(image_path, "%s.png" % id) if not path.isfile(image_file) or HEADLINE_NO_CACHE: size = int(size) font = ImageFont.truetype(path.join(font_path, font), size) width, height = font.getsize(text) ### Init surfaces image = Image.new("RGB", (width, height), (0,0,0)) alpha = Image.new("L", image.size, "black") imtext = Image.new("L", image.size, 0) draw = ImageDraw.Draw(imtext) ### Real Drawings on alpha with white color if decoration.has_key('opacity'): opacity = float(decoration['opacity']) * 255 else: opacity = 255 ### Draws text draw.text((0, 0), text, font=font, fill=opacity) ### Draws an underline if decoration.has_key('underline'): val = int(decoration['underline']) draw.line((0 + size/20, height * 4 / 5 + val, width - size/20, height * 4 / 5 + val), fill=opacity, width=size / 20) ### Draws an strikeout line if decoration.has_key('strikeout'): val = int(decoration['strikeout']) draw.line((0 + size/20, height / 2 + val, width - size/20, height / 2 + val), fill=opacity, width=size / 20) ### Alpha color black-magic alpha = ImageChops.lighter(alpha, imtext) solidcolor = Image.new("RGBA", image.size, color) immask = Image.eval(imtext, lambda p: 255 * (int(p != 0))) image = Image.composite(solidcolor, image, immask) image.putalpha(alpha) ### Rotation if decoration.has_key('rotate') and decoration['rotate']: angle = float(decoration['rotate']) if angle == 90: image = image.transpose(Image.ROTATE_90) elif angle == 180: image = image.transpose(Image.ROTATE_180) elif angle == 270: image = image.transpose(Image.ROTATE_270) else: # XXX: Bad rotation # Really bicubic transformation works only # when canvas doesn`t resize: last param is False image = image.rotate(angle, Image.BICUBIC, True) width, height = image.size ### Save image image.save(image_file, "PNG") ### Optimize png with external tool if HEADLINE_PNG_OPTIMIZER: from os import system system(HEADLINE_PNG_OPTIMIZER % {"file": image_file}) else: ### We need just dimentions width, height = Image.open(image_file).size return "%s%s/%s.png" % \ (settings.MEDIA_URL, HEADLINE_CACHE_DIR, id), width, height
for i in range(1,60,1): text = str(i) # A fully transparent image to work on, and a separate alpha channel. im = Image.new("RGB", (30, 30), (0,0,0)) alpha = Image.new("L", im.size, "black") # Make a grayscale image of the font, white on black. imtext = Image.new("L", im.size, 0) drtext = ImageDraw.Draw(imtext) font = ImageFont.truetype(fontfile, size) drtext.text(position, text, font=font, fill="white") # Add the white text to our collected alpha channel. Gray pixels around # the edge of the text will eventually become partially transparent # pixels in the alpha channel. alpha = ImageChops.lighter(alpha, imtext) # Make a solid color, and add it to the color layer on every pixel # that has even a little bit of alpha showing. solidcolor = Image.new("RGBA", im.size, color) immask = Image.eval(imtext, lambda p: 255 * (int(p != 0))) im = Image.composite(solidcolor, im, immask) # These two save()s are just to get demo images of the process. # im.save("transcolor.png", "PNG") # alpha.save("transalpha.png", "PNG") # Add the alpha channel to the image, and save it out. im.putalpha(alpha) im.save(text+".png", "PNG")
def createImage(self, index, left, top, width, height, channelAdjustment, color, imageCache=None, cacheId=None): use_cache = imageCache != None if cacheId == None: cacheId = int(index) imageFiles = self.pdc.images[index].imageFiles channelConfigurationObject = retrieve_object('ChannelConfiguration') id_to_channel_map = { 0:'R', 1:'G', 2:'B' } for c in channelAdjustment.keys(): if not c in 'RGB': i = len(id_to_channel_map) id_to_channel_map[i] = c img_dict = {} rect = None img_size = None any_rgb_adjustment_changed = False if use_cache: if not cacheId in imageCache: imageCache[cacheId] = {} files_cached = ('files' in imageCache[cacheId]) region = (left, top, width, height) if files_cached: oldRegion = imageCache[cacheId]['region'] if oldRegion != region: files_cached = False if not files_cached: imageCache[cacheId]['files'] = {} imageCache[cacheId]['region'] = region else: files_cached = False for name,path in imageFiles: name, path = channelConfigurationObject.pathHook(name, path) use_image = False for c,n in self.channelMapping.iteritems(): if n != None: if name == n: use_image = True channel = c break if use_image and (channel in channelAdjustment): black, white, brightness, outline, invert, binary \ = channelAdjustment[channel] adjustment \ = (black, white, brightness, outline, invert, binary) img = None if files_cached and (channel in imageCache[cacheId]['files']): file_cached = True else: file_cached = False adjustment_changed = True if not file_cached: tmp_img = self.loadImage(path) #print 'loading image %s' % path img_type = self.getImageType(tmp_img) #print 'img_type %s' % img_type if rect == None: if width < 0: width = tmp_img.size[0] - left if height < 0: height = tmp_img.size[1] - top rect = (left, top, left + width, top + height) img = self.cropImage(tmp_img, rect) #del tmp_img img_size = img.size pixel_arr = self.convertImageToByteArray(img, img_type) #print 'min=%d, max=%d, mean=%d, median=%d' % (numpy.min(pixel_arr), numpy.max(pixel_arr), numpy.mean(pixel_arr), numpy.median(pixel_arr)) if use_cache: imageCache[cacheId]['files'][channel] = {} imageCache[cacheId]['files'][channel]['raw_pixels'] = pixel_arr.copy() imageCache[cacheId]['files'][channel]['image_size'] = img_size else: pixel_arr = imageCache[cacheId]['files'][channel]['raw_pixels'] img_size = imageCache[cacheId]['files'][channel]['image_size'] oldAdjustment = imageCache[cacheId]['files'][channel]['adjustment'] pixel_arr = pixel_arr.copy() if oldAdjustment == adjustment: adjustment_changed = False if adjustment_changed: if use_cache: imageCache[cacheId]['files'][channel]['adjustment'] = adjustment if channel in 'RGB': any_rgb_adjustment_changed = True pixel_arr = self.adjustImage(img_size, pixel_arr, black, white, brightness, outline, invert, binary) img = self.convertByteArrayToImage(pixel_arr, img_size) #del pixel_arr if use_cache: imageCache[cacheId]['files'][channel]['processed_img'] = img.copy() else: img = imageCache[cacheId]['files'][channel]['processed_img'] img_dict[channel] = img #del img if img_size == None: if width < 0 or height < 0: width = 1 height = 1 img_size = (width, height) imgs = [] #if color: for i in xrange(len(id_to_channel_map)): c = id_to_channel_map[i] if not c in img_dict: img_dict[c] = Image.new('L', img_size) imgs.append(img_dict[c]) #else: # if len(img_dict) > 0: # imgs.append(img_dict.values()[0]) # else: # imgs.append(Image.new('L', img_size)) #del img_dict channels = channelAdjustment.keys() #channels.sort() rgb_channels_changed = True if files_cached and not any_rgb_adjustment_changed: oldChannels = imageCache[cacheId]['channels'] bool_array = [(c in oldChannels) == (c in channels) for c in 'RGB'] if numpy.all(bool_array): rgb_channels_changed = False if files_cached: oldColor = imageCache[cacheId]['color'] if color != oldColor: rgb_channels_changed = True if use_cache: imageCache[cacheId]['channels'] = channels imageCache[cacheId]['color'] = color if not rgb_channels_changed: merged_img = imageCache[cacheId]['merged_image'] else: if color: merged_img = Image.merge('RGB', imgs[:3]) else: merged_img = None for c in 'RGB': if c in channelAdjustment: merged_img = img_dict[c] break if merged_img == None: merged_img = Image.new('L', img_size) #print ' merging gray-scale image...' #print ' ', imgs[0].mode, imgs[1].mode, imgs[2].mode #ie = ImageEnhance.Contrast(merged_img) #merged_img = ie.enhance(0.0) if use_cache: imageCache[cacheId]['merged_image'] = merged_img.copy() del imgs[:3] if len(imgs) > 0: #del imgs[:3] while len(imgs) > 1: img1,img2 = imgs[0],imgs[1] tmp = ImageChops.lighter(img1, img2) del imgs[0]#, img1, img2 imgs[0] = tmp #imgs[0].save('/home/benjamin/tmp.tif') if imgs[0].mode != merged_img.mode: imgs[0] = imgs[0].convert(merged_img.mode) #imgs[0].save('/home/benjamin/tmp_rgb.tif') #merged_img.save('/home/benjamin/merged.tif') tmp = ImageChops.lighter(merged_img, imgs[0]) #tmp.save('/home/benjamin/merged_tmp.tif') del merged_img merged_img = tmp #del imgs[:] #del imgs #if merged_img.mode != 'RGB': # merged_img = merged_img.convert('RGB') #merged_img.save('/home/benjamin/rgb.tif') return merged_img
def r1(self): self.im3=ImageChops.lighter(self.im,self.im0) self.tkimage.paste(self.im3)
for i in range(1, 60, 1): text = str(i) # A fully transparent image to work on, and a separate alpha channel. im = Image.new("RGB", (30, 30), (0, 0, 0)) alpha = Image.new("L", im.size, "black") # Make a grayscale image of the font, white on black. imtext = Image.new("L", im.size, 0) drtext = ImageDraw.Draw(imtext) font = ImageFont.truetype(fontfile, size) drtext.text(position, text, font=font, fill="white") # Add the white text to our collected alpha channel. Gray pixels around # the edge of the text will eventually become partially transparent # pixels in the alpha channel. alpha = ImageChops.lighter(alpha, imtext) # Make a solid color, and add it to the color layer on every pixel # that has even a little bit of alpha showing. solidcolor = Image.new("RGBA", im.size, color) immask = Image.eval(imtext, lambda p: 255 * (int(p != 0))) im = Image.composite(solidcolor, im, immask) # These two save()s are just to get demo images of the process. # im.save("transcolor.png", "PNG") # alpha.save("transalpha.png", "PNG") # Add the alpha channel to the image, and save it out. im.putalpha(alpha) im.save(text + ".png", "PNG")
def diff_image(img1, img2): return ImageChops.lighter(img1, img2)