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')
Example #2
0
    def draw_baselines(self, img_in):
        img_out = img_in.copy()
        draw = ImageDraw.Draw(img_out)
    
        prev_floor = 0
        w, h = img_out.size
    
        gap_color = ImageColor.getrgb('#ccccFF')
    
        lines = scrape.calc_lines(scrape.font_metrics(), 7)

        for i, (ceiling, base, floor) in enumerate(lines):

            # draw the baseline
            color = ImageColor.getrgb("#ffdddd")
            if not base:
                base = floor -2
                color = ImageColor.getrgb("red")
    
            draw.line([(0, base), (w, base)], fill=color)
            
            # shade gap between the lines
            draw.rectangle((0, prev_floor, w, ceiling), fill=gap_color)
            prev_floor = floor +1
                
        # shade final gap:
        draw.rectangle((0, prev_floor, w, h), fill=gap_color)
    
        # now draw the text back over the baselines:
        img_out = ImageChops.darker(img_in, img_out)

        # uncomment to zoom in for debugging
        # img_out = img_out.resize((w *2 , h* 2))

        return img_out
Example #3
0
    def HighlightRects(self, pngfile, highlightrects):
        # large libraries.  load only if necessary
        import Image, ImageDraw, ImageEnhance, ImageChops

        dkpercent = 70

        p1 = Image.new("RGB", (500, 500))
        ff = StringIO()

        pfp = Image.open(pngfile)
        swid, shig = pfp.getbbox()[2:]

        dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0)
        ddpfp = ImageDraw.Draw(dpfp)
        for highlightrect in highlightrects:
            mrect = re.match("rect_(\d+),(\d+)_(\d+),(\d+)$", highlightrect)
            if mrect:
                rect = (int(mrect.group(1)), int(mrect.group(2)), int(mrect.group(3)), int(mrect.group(4)))
                srect = (rect[0] * swid / 1000, rect[1] * swid / 1000, rect[2] * swid / 1000, rect[3] * swid / 1000)
                ddpfp.rectangle(srect, (255, 255, 255))

        cpfp = ImageChops.darker(pfp, dpfp)

        ff = StringIO()
        cpfp.save(ff, "png")
        return ff.getvalue()
Example #4
0
def matchTemplate(searchImage, templateImage):
    minScore = -1000
    matching_xs = 0
    matching_ys = 0
    # convert images to "L" to reduce computation by factor 3 "RGB"->"L"
    searchImage = searchImage.convert(mode="L")
    templateImage = templateImage.convert(mode="L")
    searchWidth, searchHeight = searchImage.size
    templateWidth, templateHeight = templateImage.size
    # make a copy of templateImage and fill with color=1
    templateMask = Image.new(mode="L", size=templateImage.size, color=1)
    # loop over each pixel in the search image
    for xs in range(searchWidth - templateWidth + 1):
        for ys in range(searchHeight - templateHeight + 1):
            # for ys in range(10):
            # set some kind of score variable to "All equal"
            score = templateWidth * templateHeight
            # crop the part from searchImage
            searchCrop = searchImage.crop((xs, ys, xs + templateWidth, ys + templateHeight))
            diff = ImageChops.difference(templateImage, searchCrop)
            notequal = ImageChops.darker(diff, templateMask)
            countnotequal = sum(notequal.getdata())
            score -= countnotequal

            if minScore < score:
                minScore = score
                matching_xs = xs
                matching_ys = ys

    if minScore > 100:
        print "Location=", (matching_xs, matching_ys), "Score=", minScore
        quit()
Example #5
0
    def do_darker(self):
        """usage: darker <image:pic1> <image:pic2>

        Pop the two top images, push an image of the darker pixels of both.
        """
        import ImageChops
        image1 = self.do_pop()
        image2 = self.do_pop()
        self.push(ImageChops.darker(image1, image2))
Example #6
0
    def do_darker(self):
        """usage: darker <image:pic1> <image:pic2>

        Pop the two top images, push an image of the darker pixels of both.
        """
        import ImageChops
        image1 = self.do_pop()
        image2 = self.do_pop()
        self.push(ImageChops.darker(image1, image2))
def overlying(picspath,filename,imgnumlist,lying):
    #TODO lying is about the overlying type
    
    for i in range(0,len(imgnumlist)-1):
        if i==0:
            imageall=Image.open(picspath+filename+'-'+str(imgnumlist[0])+'.tiff')
            continue
        else:
            imgtmp=Image.open(picspath+filename+'-'+str(imgnumlist[i])+'.tiff')
            imageall=ImageChops.darker(imgtmp,imageall)
            imgtmp=None
            continue
    return imageall
Example #8
0
def matchTemplate(searchImage, templateImage):
    minScore = -1000
    matching_xs = 0
    matching_ys = 0
    # convert images to "L" to reduce computation by factor 3 "RGB"->"L"
    searchImage = searchImage.convert(mode="L")
    templateImage = templateImage.convert(mode="L")
    searchWidth, searchHeight = searchImage.size
    templateWidth, templateHeight = templateImage.size
    # make a copy of templateImage and fill with color=1
    templateMask = Image.new(mode="L", size=templateImage.size, color=1)
    #loop over each pixel in the search image
    xs = 0
    for ys in range(searchHeight - templateHeight + 1):
        #for ys in range(10):
        #set some kind of score variable to "All equal"
        score = templateWidth * templateHeight
        # crop the part from searchImage
        searchCrop = searchImage.crop(
            (xs, ys, xs + templateWidth, ys + templateHeight))
        diff = ImageChops.difference(templateImage, searchCrop)
        notequal = ImageChops.darker(diff, templateMask)
        countnotequal = sum(notequal.getdata())
        score -= countnotequal

        if minScore < score:
            minScore = score
            matching_ys = ys
        elif score == templateWidth * templateHeight:
            print "Conflicting score", score, (matching_xs, matching_ys), (xs,
                                                                           ys)
            return None

    #print "  - Location=",(matching_xs, matching_ys), "Score=",minScore
    im1 = Image.new('RGB', (searchWidth, searchHeight), (80, 147, 0))
    im1.paste(templateImage, ((matching_xs), (matching_ys)))
    #searchImage.show()
    #im1.show()
    #im1.save('template_matched_in_search.png')
    return matching_ys
Example #9
0
def matchTemplate(searchImage, templateImage):
    minScore = -1000
    matching_xs = 0
    matching_ys = 0
    # convert images to "L" to reduce computation by factor 3 "RGB"->"L"
    searchImage = searchImage.convert(mode="L")
    templateImage = templateImage.convert(mode="L")
    searchWidth, searchHeight = searchImage.size
    templateWidth, templateHeight = templateImage.size
    # make a copy of templateImage and fill with color=1
    templateMask = Image.new(mode="L", size=templateImage.size, color=1)
    #loop over each pixel in the search image
    xs = 0
    for ys in range(searchHeight-templateHeight+1):
    #for ys in range(10):
        #set some kind of score variable to "All equal"
        score = templateWidth*templateHeight
        # crop the part from searchImage
        searchCrop = searchImage.crop((xs,ys,xs+templateWidth,ys+templateHeight))
        diff = ImageChops.difference(templateImage, searchCrop)
        notequal = ImageChops.darker(diff,templateMask)
        countnotequal = sum(notequal.getdata())
        score -= countnotequal

        if minScore < score:
            minScore = score
            matching_ys = ys
        elif score == templateWidth*templateHeight :
            print "Conflicting score", score, (matching_xs, matching_ys), (xs, ys)
            return None
        
    print "  - Location=",(matching_xs, matching_ys), "Score=",minScore
    im1 = Image.new('RGB', (searchWidth, searchHeight), (80, 147, 0))
    im1.paste(templateImage, ((matching_xs), (matching_ys)))
    #searchImage.show()
    #im1.show()
    #im1.save('template_matched_in_search.png')
    return matching_ys
Example #10
0
def WritePNGpage(pdffile, npage, imgpixwidth, pngfile, highlightrects):
    #print 'Content-type: text/html\n\n<h1>%s</h1><p>pdffile %s' % (pngfile, pdffile); sys.exit(0)
    if not os.path.isfile(pngfile):
        cmd = 'convert -quiet -density 192 %s[%d] -resize %d %s > /dev/null 2>&1' % (
            SubParen(pdffile), npage - 1, imgpixwidth, SubParen(pngfile))
        os.system(cmd)
    if not highlightrects or not os.path.isfile(pngfile):
        fin = open(os.path.isfile(pngfile) and pngfile or "pngnotfound.png")
        print "Content-type: image/png\n"
        print fin.read()
        fin.close()
        return

    # large libraries.  load only if necessary
    import Image, ImageDraw, ImageEnhance, ImageChops

    dkpercent = 70

    p1 = Image.new("RGB", (500, 500))
    ff = StringIO()

    pfp = Image.open(pngfile)
    swid, shig = pfp.getbbox()[2:]

    dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0)
    ddpfp = ImageDraw.Draw(dpfp)
    for rect in highlightrects:
        srect = (rect[0] * swid / 1000, rect[1] * swid / 1000,
                 rect[2] * swid / 1000, rect[3] * swid / 1000)
        ddpfp.rectangle(srect, (255, 255, 255))

    cpfp = ImageChops.darker(pfp, dpfp)

    ff = StringIO()
    cpfp.save(ff, "png")
    print "Content-type: image/png\n"
    print ff.getvalue()
    ff.close()
Example #11
0
 def r2(self):
     self.im3=ImageChops.darker(self.im,self.im0)
     self.tkimage.paste(self.im3)
Example #12
0
for i in range(1,len(aa)):
     imagetempaa=imagetemp.transform((aa[i]-aa[i-1],25),Image.EXTENT,(aa[i-1]+scann.get(aa[i-1]),0,aa[i]+1,25))
     temppics.append(imagetempaa)
     
#os.system('gswin32c.exe -q -sDEVICE=pnggray -dBATCH -dNOPAUSE -dFirstPage=1 -dLastPage=20 -r150 -sOutputFile="D:\\tmp\\cover-%d.png" "D:\\1.pdf"')

imglist=[]
imageall = None
for i in range(1,670):
    if i==1:
        imageall=Image.open('D:\\tmp\\pic-'+str(i)+'.png')
        continue
    else:
        imgtmp=Image.open('D:\\tmp\\pic-'+str(i)+'.png')
        imageall=ImageChops.darker(imgtmp,imageall)
        imgtmp=None
        continue
#for i in range(0,len(temppics)):
#   temppics[i].save('D:\\tmp\\'+str(i)+'.png')

##for i in line.keys():
##    rowh = line.get(i)
##    imagetemp=img.transform((w,rowh),Image.EXTENT,(0,i,w,i+rowh))
##    scanh=scanpic(imagetemp,'h')
##    f = getfl(scanh,'f')
##    e = getfl(scanh,'l')
   ## if (scanh>=
##for i in range(0,len(listtmp)):
##    if i==0:
##        row=img.transform((w,listtmp[i]+1),Image.EXTENT,(0,0,w,listtmp[i]+1))
Example #13
0
def cropimg(request, format, srcdoc, page, cropping):
    page = int(page)
    cropping = cropping or ""

    pdfurl, pdffile, imgstem, qtail = GetSrcDoc(request, srcdoc)
    # It is possible that imgstem is None.
    if (not pdfurl) or (not imgstem):
        return HttpResponse(open(
            os.path.join(settings.MEDIA_DIR, 'images', '404.png'),
            "rb").read(),
                            mimetype='image/png')

    if not os.path.isfile(pdffile):
        # possibly should download it
        return HttpResponse(open(
            os.path.join(settings.MEDIA_DIR, 'images', '404.png'),
            "rb").read(),
                            mimetype='image/png')

    imgfile = "%s_%04d.png" % (imgstem, page)
    imgpixwidth = 800

    if not os.path.isfile(imgfile):
        cmd = 'convert -quiet -density 192 "%s[%d]" -resize %d -define png:color-type=2 "%s" > /dev/null 2>&1' % (
            pdffile, page - 1, imgpixwidth, imgfile)
        os.system(cmd)

    croppings = filter(lambda x: x, cropping.split("/"))

    if not croppings:
        if os.path.getsize(imgfile) > pngfilesizeconsiderlimit:
            jpgimgfile = "%s_%04d.jpg" % (imgstem, page)
            if not os.path.isfile(jpgimgfile):
                cmd = 'convert -quiet -density 192 "%s[%d]" -resize %d "%s" > /dev/null 2>&1' % (
                    pdffile, page - 1, imgpixwidth, jpgimgfile)
                os.system(cmd)
            #print "\n\njpg/png sizes", os.path.getsize(jpgimgfile), os.path.getsize(imgfile)
            if os.path.getsize(jpgimgfile) < os.path.getsize(
                    imgfile) / pngfilesizejpgfactor:
                return HttpResponse(open(jpgimgfile, "rb").read(),
                                    mimetype='image/jpeg')
        return HttpResponse(open(imgfile, "rb").read(), mimetype='image/png')

    # png images began causing problems by loading in mode="I" instead of mode="RGB"
    # fixed with the -define png:color-type=2 setting above

    # here on is executed only if there is a cropping to be applied
    pfp = Image.open(imgfile)
    #pfp = Image.open(jpgimgfile)
    swid, shig = pfp.getbbox()[2:]

    highlightrects = []
    clip = None
    for crop in croppings:
        mhr = re.match('(rect|clip)_(\d+),(\d+)_(\d+),(\d+)$', crop)
        if mhr:
            dim = (int(mhr.group(2)) * swid / 1000, int(mhr.group(3)) *
                   swid / 1000, int(mhr.group(4)) * swid / 1000,
                   int(mhr.group(5)) * swid / 1000)
            if mhr.group(1) == "rect":
                highlightrects.append(dim)
            if mhr.group(1) == "clip":
                clip = dim

    # build the mask which is a darker version of the original
    # then plots white rectangle over it, which when ImageChops.darker() is applied
    # between the two favours the lighter original in instead of the white rectangles
    if highlightrects:
        # print pfp.mode  must not be I
        dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0)
        ddpfp = ImageDraw.Draw(dpfp)
        for rect in highlightrects:
            ddpfp.rectangle(rect, (255, 255, 255))
        cpfp = ImageChops.darker(pfp, dpfp)  # makes darker of the two
    else:
        cpfp = pfp

    # pngprev is about whether the crop is applied or is masked so you can see it in place
    if clip:
        if format == "pngprev":
            p1 = Image.new("RGB", (swid, shig))
            dp1 = ImageDraw.Draw(p1)
            dp1.rectangle((0, 0, swid, shig), (155, 10, 10))
            dp1.rectangle(clip, (255, 255, 255))
            cpfp = ImageChops.darker(p1, cpfp)  # makes darker of the two
        else:
            cpfp = cpfp.crop(clip)

    # actually if the png version is WAY too large we revert to giving you a jpg because it's probably a dirty scan
    imgmimetype = 'image/png'
    imgout = cStringIO.StringIO()
    cpfp.save(imgout, "png")

    if imgout.tell() > pngfilesizeconsiderlimit:
        jpgimgout = cStringIO.StringIO()

        # Problem - We need horsell to have jpeg writer installed
        try:
            cpfp.save(jpgimgout, "jpeg")
            if jpgimgout.tell() < imgout.tell() / pngfilesizejpgfactor:
                imgout = jpgimgout
                imgmimetype = 'image/jpeg'
        except IOError, e:
            logging.warning(str(e.args))
            assert e.args[0] == 'encoder jpeg not available', e.args
Example #14
0
def threshold(im, thres):
    w, h = im.size
    imt = im.point(lambda i: i - thres, "1")
    return ImageChops.darker(imt, Image.new("1", (w, h), 1))
Example #15
0
 def take_snapshot(self, screen):
     snap = super(StringRegion, self).take_snapshot(screen)
     thresh = Image.new("RGB", snap.size, "#999999")
     mono = ImageChops.darker(snap, thresh)
     mono = ImageOps.autocontrast(mono, 0)
     return mono # .resize((w *2, h * 2))
Example #16
0
def cropimg(request, format, srcdoc, page, cropping):
    page = int(page)
    cropping = cropping or ""

    pdfurl, pdffile, imgstem, qtail = GetSrcDoc(request, srcdoc)
    # It is possible that imgstem is None.
    if (not pdfurl) or (not imgstem):
        return HttpResponse(open(os.path.join(settings.MEDIA_DIR, 'images', '404.png'), "rb").read(), mimetype='image/png')

    if not os.path.isfile(pdffile):
            # possibly should download it
        return HttpResponse(open(os.path.join(settings.MEDIA_DIR, 'images', '404.png'), "rb").read(), mimetype='image/png')

    imgfile = "%s_%04d.png" % (imgstem, page)
    imgpixwidth = 800
    
    if not os.path.isfile(imgfile):
        cmd = 'convert -quiet -density 192 "%s[%d]" -resize %d -define png:color-type=2 "%s" > /dev/null 2>&1' % (pdffile, page-1, imgpixwidth, imgfile)
        os.system(cmd)

    croppings = filter(lambda x:x, cropping.split("/"))
    
    if not croppings:
        if os.path.getsize(imgfile) > pngfilesizeconsiderlimit:
            jpgimgfile = "%s_%04d.jpg" % (imgstem, page)
            if not os.path.isfile(jpgimgfile):
                cmd = 'convert -quiet -density 192 "%s[%d]" -resize %d "%s" > /dev/null 2>&1' % (pdffile, page-1, imgpixwidth, jpgimgfile)
                os.system(cmd)
            #print "\n\njpg/png sizes", os.path.getsize(jpgimgfile), os.path.getsize(imgfile)
            if os.path.getsize(jpgimgfile) < os.path.getsize(imgfile) / pngfilesizejpgfactor:
                return HttpResponse(open(jpgimgfile, "rb").read(), mimetype='image/jpeg')
        return HttpResponse(open(imgfile, "rb").read(), mimetype='image/png')


    # png images began causing problems by loading in mode="I" instead of mode="RGB"
    # fixed with the -define png:color-type=2 setting above

    # here on is executed only if there is a cropping to be applied
    pfp = Image.open(imgfile)    
    #pfp = Image.open(jpgimgfile)
    swid, shig = pfp.getbbox()[2:]
    
    highlightrects = [ ]
    clip = None
    for crop in croppings:
        mhr = re.match('(rect|clip)_(\d+),(\d+)_(\d+),(\d+)$', crop)
        if mhr:
            dim = (int(mhr.group(2))*swid/1000, int(mhr.group(3))*swid/1000, int(mhr.group(4))*swid/1000, int(mhr.group(5))*swid/1000)
            if mhr.group(1) == "rect":
                highlightrects.append(dim)
            if mhr.group(1) == "clip":
                clip = dim
        
        
    # build the mask which is a darker version of the original
    # then plots white rectangle over it, which when ImageChops.darker() is applied 
    # between the two favours the lighter original in instead of the white rectangles
    if highlightrects:
        # print pfp.mode  must not be I
        dpfp = ImageEnhance.Brightness(pfp).enhance(dkpercent / 100.0)
        ddpfp = ImageDraw.Draw(dpfp)
        for rect in highlightrects:
            ddpfp.rectangle(rect, (255, 255, 255))
        cpfp = ImageChops.darker(pfp, dpfp) # makes darker of the two
    else:
        cpfp = pfp

    # pngprev is about whether the crop is applied or is masked so you can see it in place
    if clip:
        if format == "pngprev":
            p1 = Image.new("RGB", (swid, shig))
            dp1 = ImageDraw.Draw(p1)
            dp1.rectangle((0,0,swid,shig), (155, 10, 10))
            dp1.rectangle(clip, (255, 255, 255))
            cpfp = ImageChops.darker(p1, cpfp) # makes darker of the two
        else:
            cpfp = cpfp.crop(clip)
    
    # actually if the png version is WAY too large we revert to giving you a jpg because it's probably a dirty scan
    imgmimetype ='image/png'
    imgout = cStringIO.StringIO()
    cpfp.save(imgout, "png")
    
    if imgout.tell() > pngfilesizeconsiderlimit:
        jpgimgout = cStringIO.StringIO()
        
# Problem - We need horsell to have jpeg writer installed
        try:  
            cpfp.save(jpgimgout, "jpeg")
            if jpgimgout.tell() < imgout.tell() / pngfilesizejpgfactor:
                imgout = jpgimgout
                imgmimetype = 'image/jpeg'
        except IOError, e:
            logging.warning(str(e.args))
            assert e.args[0] == 'encoder jpeg not available', e.args
Example #17
0
i1.save("/tmp/i1.jpg")
print "I1, orig, saved."
i2 = ImageChops.duplicate(i1)
marked = Image.eval(marked, bw)

merge = i2

# calculate spread that works well with your scaling factor
spread = int(round(i1.size[0] / (scaling_factor * 75.)))

# wherever there's a dark pixel, darken all pixels within spread pixels
for x in range(-spread, spread, 1):
    for y in range(-spread, spread, 1):
        print spread, x, y
        newi = ImageChops.offset(i2, x, y)
        merge = ImageChops.darker(merge, newi)
i2 = merge
i2.save("/tmp/i2.jpg")
print "I2, mask, saved"
i3 = i2.resize((i1.size[0], i1.size[1]))
i3.save("/tmp/i3.jpg")
print "I3 saved"

i4 = Image.eval(i3, bw)

rot = i1.rotate(.5)
i5 = ImageChops.darker(rot, i4)

rot = i1.rotate(1.)
i6 = ImageChops.darker(rot, i4)