Exemple #1
0
 def images_equal(image1, image2, acceptable_rms = 10):
     try:
         img1 = Image.open(image1)
         img2 = Image.open(image2)
     except:
         return False
     try:
         diff = ImageChops.difference(img1, img2)
     except ValueError:
         return False
     h = ImageChops.difference(img1, img2).histogram()
     sq = (value*((idx%256)**2) for idx, value in enumerate(h))
     sum_of_squares = sum(sq)
     rms = math.sqrt(sum_of_squares/float(img1.size[0] * img1.size[1]))
     return rms <= acceptable_rms
Exemple #2
0
def autocrop(im, bgcolor, borderWidth=0):
    if im.mode != 'RGB':
        im = im.convert('RGB')
    bg = Image.new('RGB', im.size, bgcolor)
    diff = ImageChops.difference(im, bg)
    bbox = diff.getbbox()
    if bbox:
        if borderWidth > 0:
            (x0, y0, x2, y2) = bbox

            if x0 > borderWidth:
                x0 = x0 - borderWidth
            else:
                x0 = 0

            if y0 > borderWidth:
                y0 = y0 - borderWidth
            else:
                y0 = 0

            if x2 + borderWidth < im.size[0]:
                x2 = x2 + borderWidth
            else:
                x2 = im.size[0]

            if y2 + borderWidth < im.size[1]:
                y2 = y2 + borderWidth
            else:
                y2 = im.size[1]

            bbox = (x0, y0, x2, y2)

        return im.crop(bbox)
    return im
    def testExecute(self):
        """
        """
        self.run()
        plugin = self.getPlugin()
        ################################################################################
        # Compare XSDataResults
        ################################################################################
        strExpectedOutput = self.readAndParseFile(
            self.getReferenceDataOutputFile())
        EDVerbose.DEBUG("Checking obtained result...")

        xsDataResultObtained = plugin.getDataOutput()
        EDAssert.strAlmostEqual(self.xsDataResultReference.marshal(),
                                xsDataResultObtained.marshal(),
                                "XSDataResult output are the same")
        ################################################################################
        # Compare image Files
        ################################################################################
        outputData = Image.open(self.outputFile)
        referenceData = Image.open(
            os.path.join(self.getTestsDataImagesHome(),
                         os.path.basename(self.outputFile)))
        delta = ImageChops.difference(outputData, referenceData)
        deltaColor = delta.getextrema()
        i = 0
        for color in deltaColor:
            EDAssert.lowerThan(
                color[1], 12, "Maximum tone variation is %s for channel %s" %
                (color[1], "RGBA"[i]))
            i += 1
Exemple #4
0
    def refresh(self, image, bbox=None):

        # find the difference from the current framebuffer
        bbox = ImageChops.difference(image, self.image).getbbox()
        if bbox != None:

            (left, top, right, bottom) = bbox
            right *= 8
            right /= 8
            left /= 8
            left *= 8
            top /= 8
            bottom += 7
            bottom /= 8

            # for each Nx8 row segment
            for row in xrange(top, bottom):
                y = row * 8
                update = ''
                # build a horizontal array of 8-bit vertical stripes
                for x in xrange(left, right, 8):
                    # get an 8x8 chunk and rotate into the display's vertical address orientation
                    chunk = image.crop(
                        (x, y, x + 8, y + 8)).transpose(Image.ROTATE_270)
                    # add this 8x8 chunk to the update
                    update += chunk.tostring()

                # write out the update for this Nx8 row
                self.display.graphicWrite(update, left * 4 + row)

            # update the framebuffer
            self.image = image
Exemple #5
0
    def refresh(self, image, bbox=None):

        # find the difference from the current framebuffer
        if bbox == None:
            bbox = ImageChops.difference(image, self.image).getbbox()

        if bbox != None:

            (left, top, right, bottom) = bbox
            left /= 8
            left *= 8
            right *= 8
            right /= 8

            # get the pixels to be updated
            update = image.crop((left, 0, right, self.display.H))
            # rotate the update into the display's vertical address orientation
            update = update.transpose(Image.ROTATE_270).transpose(
                Image.FLIP_LEFT_RIGHT)
            # send the update
            update = update.tostring()
            self.write(update, left * (self.display.H / 8))

            # update the framebuffer
            self.image = image
Exemple #6
0
def repeat():
	global capture
	global camera_index
	global first_frame
	global last_frame
	global frame_decount
	global last_bubble_time

	frame = cv.QueryFrame(capture)
	cv.ShowImage("w1", frame)
	c = cv.WaitKey(10)

	image = Image.fromstring("RGB", [frame.width, frame.height], frame.tostring())
	if not first_frame:
		diff = ImageChops.difference(image, last_frame)
		h = diff.histogram()
		sq = (value*(idx**2) for idx, value in enumerate(h))
		sum_of_squares = sum(sq)
		rms = math.sqrt(sum_of_squares/float(image.size[0] * last_frame.size[1]))
		if rms > 579.00 and frame_decount == 0:
			now = time.time()
			delta = (now - last_bubble_time)
			row_key = '-'.join(['row',str(now)])
			table.put(row_key, {'info:delta': str(delta), 'info:date': str(datetime.datetime.now()).split('.')[0], 'info:rms': str(rms), 'info:height': str(frame.height), 'info:width': str(frame.width)})
			print("Gas Release Detected: (Delta: %f)" % (delta))
			print("Record Saved -> %s" % (row_key))
			frame_decount = 40
			last_bubble_time = now
		elif frame_decount > 0:
			frame_decount = frame_decount - 1

	last_frame = image
	first_frame = False
Exemple #7
0
def avgentropy(imgset, imgs):
	idxs = range(0, 30)
	entropies = []
	# precalculate all entropies
	for i in range(0, 29):
		diff = ImageChops.difference(imgs[i], imgs[i+1])
		entropies.append(image_entropy(diff))
	print entropies

	avg = []
	# average of the entropy of the difference with previous & next images.
	avg.append(entropies[0])
	for i in range(1,29):
		avg.append((entropies[i-1] + entropies[i]) / 2.)
		print avg[-1]
	avg.append(entropies[-1])
	#idxs = range(0, 30)
	#OFFSET = 1
	#avg = []
	# compare all images in the specified range
	#for i in idxs:
	#	ent = []
	#	idxs2 = range(max(0, i-OFFSET), min(i+OFFSET+1, 30))
	#	for j in idxs2:
	#		if i != j:
	#			diff = ImageChops.difference(imgs[i], imgs[j])
	#			ent.append(image_entropy(diff))
	#	avg.append(np.mean(ent))
	# save a plot of the average entropy array
	plt.plot(idxs, avg, 'bo-')
	plt.axvline(result[imgset-1]-1, color="r")
	plt.savefig("avg-%i-%i.png" % (imgset, len(idxs)))
	plt.clf()
	return avg
Exemple #8
0
def imagecompare(imgfile1, imgfile2):
    try:
        import ImageChops, Image
    except ImportError:
        raise Exception, 'Python-Imaging package not installed'
    try:
        diffcount = 0.0
        im1 = Image.open(imgfile1)
        im2 = Image.open(imgfile2)

        imgcompdiff = ImageChops.difference(im1, im2)
        diffboundrect = imgcompdiff.getbbox()
        imgdiffcrop = imgcompdiff.crop(diffboundrect)

        data = imgdiffcrop.getdata()

        seq = []
        for row in data:
            seq += list(row)

        for i in xrange(0, imgdiffcrop.size[0] * imgdiffcrop.size[1] * 3, 3):
            if seq[i] != 0 or seq[i+1] != 0 or seq[i+2] != 0:
                diffcount = diffcount + 1.0
        
        diffImgLen = imgcompdiff.size[0] * imgcompdiff.size[1] * 1.0
        diffpercent = (diffcount * 100) / diffImgLen
        return diffpercent
    except IOError:
        raise Exception, 'Input file does not exist'
Exemple #9
0
def autocrop(im, bgcolor, borderWidth = 0):
    if im.mode != 'RGB':
        im = im.convert('RGB')
    bg = Image.new('RGB', im.size, bgcolor)
    diff = ImageChops.difference(im, bg)
    bbox = diff.getbbox()
    if bbox:
        if borderWidth > 0:
            (x0,y0,x2,y2) = bbox

            if x0 > borderWidth:
                x0 = x0 - borderWidth
            else:
                x0 = 0

            if y0 > borderWidth:
                y0 = y0 - borderWidth
            else:
                y0 = 0

            if x2 + borderWidth < im.size[0]:
                x2 = x2 + borderWidth
            else:
                x2 = im.size[0]

            if y2 + borderWidth < im.size[1]:
                y2 = y2 + borderWidth
            else:
                y2 = im.size[1]

            bbox = (x0,y0,x2,y2)

        return im.crop(bbox)
    return im
Exemple #10
0
 def _equal(self, img1, img2):
     """
     Checks if two screenshots are identical.
     @param img1: first screenshot to check
     @param img2: second screenshot to check
     """
     return ImageChops.difference(img1, img2).getbbox() is None
Exemple #11
0
def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"
    h = ImageChops.difference(im1, im2).histogram()
    # calculate rms
    return math.sqrt(reduce(operator.add,
	map(lambda h, i: h*(i**2), h, range(1024))
	) / (float(im1.size[0]) * im1.size[1]))
Exemple #12
0
def autocrop(im, bgcolor):
    bg = Image.new(im.mode, im.size, bgcolor)
    diff = ImageChops.difference(im, bg)
    bbox = diff.getbbox()
    print "bbox",bbox
    if bbox: return im.crop(bbox) # cropped
    else: return im # no contents
def recognize(img, bounds):

    # read dataset of images for each letter
    imgs = {}
    datfile = open("ads.dat", "rt")
    line = datfile.readline()
    while line!="":
        key = line[0]
        if key not in imgs:
            imgs[key] = []
        imgs[key].append(Image.open(StringIO.StringIO(line[2:-1].decode("hex"))))
        line = datfile.readline()
    datfile.close()

    # calculate difference with dataset for each boundbox
    word = ""
    for bound in bounds:
        guess = []
        total = (img.crop(bound).size)[0]*(img.crop(bound).size)[1]*1.0
        for key in imgs:
            for pattern in imgs[key]:
                diff = ImageChops.difference(img.crop(bound), pattern.resize(img.crop(bound).size, Image.NEAREST))
                pixels = list(diff.getdata())
                samePixCnt = sum(i==0 for i in pixels)
                guess.append([samePixCnt, key])
        guess.sort(reverse=True)
        word = word+guess[0][1]
        print total, guess[0:3], guess[0][0]/total, guess[1][0]/total, guess[2][0]/total
    print word

    return word.replace("_", "")
def crop(image_file, bgcolor=ImageColor.getrgb("white")):
  image = Image.open(image_file,'r')
  mask = Image.new("RGB", image.size, bgcolor)
  diff = ImageChops.difference(image, mask)
  bbox = diff.getbbox()
  new_image = image.crop(bbox)
  new_image.save(image_file,"png")
Exemple #15
0
    def autofocus(self,step=5000):
        if self.slide.pos[2] >= 0:  step = -step
        self.slide.moveZ(-step/2)
        z_start = self.slide.pos[2]
        self.frames.fillBuffer()
        self.slide.displaceZ(step)
        z_frames = self.frames.getBuffer()

        #sample every kth plus its lth neighbor:  for k=10,l=2 sample frame 0,10,20 and 2,12,22
        k = 10
        l = 2
        sample_ind = [ind*k for ind in range(len(z_frames)/k)]
        sample_ind2 = [ind*k+l for ind in range(len(z_frames)/k)]
        f = [z_frames[ind] for ind in sample_ind]
        f2 = [z_frames[ind] for ind in sample_ind2]
        n = len(f)
        diffs = []
        for i in range(n-2):
            diffs.append(ImageChops.difference(f[i],f2[i]))
        motion = []
        for f in diffs:
            f = ImageChops.multiply(f,self.curr_mask)
            motion.append(ImageStat.Stat(f).sum[0])
        #g = Gnuplot.Gnuplot()
        #g.plot(motion)

        max_frame = scipy.argmax(motion)
        max_focus = (max_frame/float(n))*step + z_start
        self.slide.moveZ(max_focus)
        return max_focus
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()
Exemple #17
0
    def equal(self, img1, img2, skip_area=None):
        """Compares two screenshots using Root-Mean-Square Difference (RMS).
        @param img1: screenshot to compare.
        @param img2: screenshot to compare.
        @return: equal status.
        """
        if not HAVE_PIL:
            return None

        # Trick to avoid getting a lot of screen shots only because the time in the windows
        # clock is changed.
        # We draw a black rectangle on the coordinates where the clock is locates, and then
        # run the comparison.
        # NOTE: the coordinates are changing with VM screen resolution.
        if skip_area:
            # Copying objects to draw in another object.
            img1 = img1.copy()
            img2 = img2.copy()
            # Draw a rectangle to cover windows clock.
            for img in (img1, img2):
                self._draw_rectangle(img, skip_area)

        # To get a measure of how similar two images are, we use
        # root-mean-square (RMS). If the images are exactly identical,
        # this value is zero.
        diff = ImageChops.difference(img1, img2)
        h = diff.histogram()
        sq = (value * ((idx % 256)**2) for idx, value in enumerate(h))
        sum_of_squares = sum(sq)
        rms = math.sqrt(sum_of_squares/float(img1.size[0] * img1.size[1]))

        # Might need to tweak the threshold.
        return rms < 8
Exemple #18
0
def _getBounds(size, glDispID, filename, scale, rotation, partRotation):
    
    # Clear the drawing buffer with white
    glClearColor(1.0, 1.0, 1.0, 1.0)
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT)
    
    # Draw the piece in black
    glColor3f(0, 0, 0)
    adjustGLViewport(0, 0, size, size)
    rotateToView(rotation, scale)
    rotateView(*partRotation)

    glCallList(glDispID)

    # Use PIL to find the image's bounding box (sweet)
    pixels = glReadPixels(0, 0, size, size, GL_RGB,  GL_UNSIGNED_BYTE)
    img = Image.fromstring("RGB", (size, size), pixels)
    
    bg = bgCache.setdefault(size, Image.new("RGB", img.size, (255, 255, 255)))
    box = ImageChops.difference(img, bg).getbbox()

    if box is None:
        return (0, 0, 0, 0, 0, 0)  # Rendered entirely out of frame

#    if filename:
#        import os
#        rawFilename = os.path.splitext(os.path.basename(filename))[0]
#        img.save("C:\\lic\\tmp\\%s_%dx%d.png" % (rawFilename, box[2] - box[0], box[3] - box[1]))
#        print filename + "box: " + str(box if box else "No box = shit")

    # Find the bottom left corner inset, used for placing PLIItem quantity labels
    data = img.load()
    leftInset = _getLeftInset(data, size, box[1])
    bottomInset = _getBottomInset(data, size, box[0])
    return box + (leftInset - box[0], bottomInset - box[1])
Exemple #19
0
    def equal(self, img1, img2, skip_area=None):
        """Compares two screenshots using Root-Mean-Square Difference (RMS).
        @param img1: screenshot to compare.
        @param img2: screenshot to compare.
        @return: equal status.
        """
        if not HAVE_PIL:
            return None

        # Trick to avoid getting a lot of screen shots only because the time in the windows
        # clock is changed.
        # We draw a black rectangle on the coordinates where the clock is locates, and then
        # run the comparison.
        # NOTE: the coordinates are changing with VM screen resolution.
        if skip_area:
            # Copying objects to draw in another object.
            img1 = img1.copy()
            img2 = img2.copy()
            # Draw a rectangle to cover windows clock.
            for img in (img1, img2):
                self._draw_rectangle(img, skip_area)

        # To get a measure of how similar two images are, we use
        # root-mean-square (RMS). If the images are exactly identical,
        # this value is zero.
        diff = ImageChops.difference(img1, img2)
        h = diff.histogram()
        sq = (value * ((idx % 256)**2) for idx, value in enumerate(h))
        sum_of_squares = sum(sq)
        rms = math.sqrt(sum_of_squares / float(img1.size[0] * img1.size[1]))

        # Might need to tweak the threshold.
        return rms < 8
    def CreateContrast(self):
        image = self.grab_screen('comparer.png')

        diffImage = ImageChops.difference(self.baseImage, image)

        self.save_image('diff.png', diffImage)

        imageWidth, imageHeight = diffImage.size

        outlist = [(0,0,0) for x in xrange(imageWidth*imageHeight)]

        imgdata = list(diffImage.getdata())
        for x in xrange(imageWidth):
            for y in xrange(imageHeight):
                color = imgdata[y*imageWidth+x]
        ##        if color != (0,0,0):
        ##            outlist[y*imageWidth+x] = (255,0,0)
                if color[0] > 20 or color[1] > 20 or color[2] > 20:
                    outlist[y*imageWidth+x] = (255,0,0)
        ##            print color

        self.changedImage = Image.new('RGB', (imageWidth, imageHeight))
        self.changedImage.putdata(outlist)

        self.save_image('changed.png', self.changedImage)
Exemple #21
0
def showImageDifference():
    global testImage, refImage, diffImage, diffCanvas, croppedRefImage
    xsize, ysize = testImage.size
    croppedRefImage = refImage.crop((0, 0, xsize, ysize))
    diffImage = ImageChops.difference(testImage, croppedRefImage)
    diffCanvas = openImageWindow(diffImage, 'BOS Difference', diffCanvas)
    return
Exemple #22
0
def imagecompare(imgfile1, imgfile2):
    try:
        import ImageChops, Image
    except ImportError:
        raise Exception('Python-Imaging package not installed')
    try:
        diffcount = 0.0
        im1 = Image.open(imgfile1)
        im2 = Image.open(imgfile2)

        imgcompdiff = ImageChops.difference(im1, im2)
        diffboundrect = imgcompdiff.getbbox()
        imgdiffcrop = imgcompdiff.crop(diffboundrect)

        data = imgdiffcrop.getdata()

        seq = []
        for row in data:
            seq += list(row)

        for i in xrange(0, imgdiffcrop.size[0] * imgdiffcrop.size[1] * 3, 3):
            if seq[i] != 0 or seq[i+1] != 0 or seq[i+2] != 0:
                diffcount = diffcount + 1.0
        
        diffImgLen = imgcompdiff.size[0] * imgcompdiff.size[1] * 1.0
        diffpercent = (diffcount * 100) / diffImgLen
        return diffpercent
    except IOError:
        raise Exception('Input file does not exist')
Exemple #23
0
def game_logic(screen, dt, player):
    global TRACES
    im = screen_grab(box=PLAYABLE_BOX)
    #return True
    
    #im = screen_grab(box=PLAYABLE_BOX)
    im_gray = ImageOps.grayscale(im)
    
    coords = get_coords()
    if coords[0] < 0 or coords[1] < 0:
        print "Mouse out"
        return False
    
    if im.getpixel(END_GAME_OK) == (232, 97, 1):
        return True
    if im.getpixel(GET_READY) == (244, 198, 0) or im.getpixel(START_BUTTON) == (217, 83, 14):
        return True
    


    diff_array = asarray(ImageChops.difference(im_gray,BACKGROUND_GRAY))
    #grayscale_array_to_pygame(screen, diff_array)

    bird, pipes = find_elements(diff_array)
    draw_game(screen, bird, pipes)
    player.see(dt, bird, pipes)
    pygame.draw.rect(screen, BLUE, [player.x - 3, player.y - 3, 6, 6])
    font = pygame.font.SysFont("monospace", 15)
    label = font.render("%d %d"%(player.speed_y, player.accel_y), 1, (255,255,0))
    screen.blit(label, (10, FLOOR_Y + 26))
    player.play()
    

    return True
def equal(im1, im2):
    diff = ImageChops.difference(im1, im2)
    h = diff.histogram()
    sq = (value*(idx**2) for idx, value in enumerate(h))
    sum_of_squares = sum(sq)
    rms = math.sqrt(sum_of_squares/float(im1.size[0] * im1.size[1]))
    return rms
Exemple #25
0
def convert(img):
    paths = os.listdir(imgDataPath)
    for i in range(len(paths)):
        datum = Image.open(imgDataPath + paths[i])
        if ImageChops.difference(img, datum).getbbox() is None:
            return i
    return -1
	def compare_screenshots(self,approved_path, actual_path, diff_path ):
		#
		dataA = open(approved_path, 'rb').read()
		dataB = open(actual_path, 'rb').read()

		if hashlib.md5(dataA).hexdigest() != hashlib.md5(dataB).hexdigest():
			#make one size
			# ToDo 
			imageA = Image.open(approved_path)
			imageB = Image.open(actual_path)
			#if sizes not match - resize smalled
			if ( imageA.size != imageB.size ):
				#get max image size
				w_size = max( [ imageA.size[0] , imageB.size[0] ] )
				h_size = max( [ imageA.size[1] , imageB.size[1] ] )
				#resize images with max size
				imageA = imageA.resize( [ w_size , h_size ] ,Image.ANTIALIAS )
				#imageA.size = [w_size , h_size]
				imageB = imageB.resize( [ w_size , h_size ] ,Image.ANTIALIAS )
				#imageB.size = [w_size , h_size]
			
			#calculate diff
			diff = ImageChops.difference(imageA, imageB)
			#generate pretty diff image  
			light = Image.new('RGB', size=imageA.size, color=0xFFFFFF)
			mask = Image.new('L', size=imageA.size, color=0xFF)
			draw = ImageDraw.Draw(mask)
			draw.rectangle((0, 0, imageA.size[0], imageA.size[1] ), fill=0x80)
			imageA = Image.composite(imageA, light, mask)
			imageA.paste(diff, (0,0), mask)
			imageA.convert("RGB")
			imageA.save( diff_path , "PNG" )
			return True
		return False
Exemple #27
0
 def _equal(self, img1, img2):
     """
     Checks if two screenshots are identical.
     @param img1: first screenshot to check
     @param img2: second screenshot to check
     """
     return ImageChops.difference(img1, img2).getbbox() is None
def recognize(img, bounds):

    # read dataset of images for each letter
    imgs = {}
    datfile = open("ads.dat", "rt")
    line = datfile.readline()
    while line != "":
        key = line[0]
        if key not in imgs:
            imgs[key] = []
        imgs[key].append(
            Image.open(StringIO.StringIO(line[2:-1].decode("hex"))))
        line = datfile.readline()
    datfile.close()

    # calculate difference with dataset for each boundbox
    word = ""
    for bound in bounds:
        guess = []
        total = (img.crop(bound).size)[0] * (img.crop(bound).size)[1] * 1.0
        for key in imgs:
            for pattern in imgs[key]:
                diff = ImageChops.difference(
                    img.crop(bound),
                    pattern.resize(img.crop(bound).size, Image.NEAREST))
                pixels = list(diff.getdata())
                samePixCnt = sum(i == 0 for i in pixels)
                guess.append([samePixCnt, key])
        guess.sort(reverse=True)
        word = word + guess[0][1]
        print total, guess[
            0:3], guess[0][0] / total, guess[1][0] / total, guess[2][0] / total
    print word

    return word.replace("_", "")
Exemple #29
0
 def imageprocess(self):
     
     while self.isrunning:
         try:
             self.currentframedata = urllib2.urlopen(self.config['cameraurl']).read()
         except:
             continue
         
         if not self.dnd:
             
             self.currentimage = Image.open(StringIO.StringIO(self.currentframedata))
             if self.previousimage == None: self.previousimage = self.currentimage.copy()
             framedifference = ImageStat.Stat(ImageChops.difference(self.currentimage, self.previousimage)).rms
             self.rms = sum(framedifference)/len(framedifference)
             self.previousimage = self.currentimage.copy()
             self.currentimage = None              
             
             if self.rms > self.config['sensivity']:
                 self.show()
             
         gtk.gdk.threads_enter()
         try:
             if self.get_visible():
                 self.set_title(str(datetime.datetime.now()))
                 framedataloader=gtk.gdk.PixbufLoader()
                 framedataloader.write(self.currentframedata)
                 framedataloader.close()
                 self.canvas.set_from_pixbuf(framedataloader.get_pixbuf())
         finally:
             gtk.gdk.threads_leave()
    def processImage(self, im):
        im = im.resize((320, 240))
        im = ImageOps.grayscale(im)
        im = im.filter(ImageFilter.BLUR)

        if not self.prevImage:
            self.prevImage = im
            return

        imd = ImageChops.difference(im, self.prevImage)

        def mappoint(pix):
            if pix > 20:
                return 255
            else:
                return 0

        imbw = imd.point(mappoint)

        hist = imbw.histogram()
        percentWhitePix = hist[-1] / (hist[0] + hist[-1])
        motionDetected = (percentWhitePix > self.DETECTION_THRESHOLD)
        self.factory.motionStateMachine.step(motionDetected)
        motionSustained = self.factory.motionStateMachine.inSustainedMotion()

        print '%d %d' % (motionDetected, motionSustained)
        sys.stdout.flush()

        self.prevImage = im
Exemple #31
0
    def difference(self, first, second):
        import ImageChops
        from hashlib import md5
        difference = ImageChops.difference(first, second)
        diff_box = difference.getbbox()
        diffs = []
        if diff_box is not None:
            # If there is any difference, just retrieve the box
            # that has changed in the new frame
            image = first.crop((diff_box[0],
                                     diff_box[1],
                                     diff_box[2],
                                     diff_box[3]))
            size = (diff_box[2] - diff_box[0], diff_box[3] - diff_box[1])
            position = (diff_box[0], diff_box[1])
            hash = str(md5(image.tostring()).hexdigest())
            diff = {
                "hash": hash,  # Hash of the diff for checking if portion is repeated (md5 string)
                "image": image,  # Portion of the image <Image>
                "position": position,  # Position of the portion in the frame (x, y)
                "size": size  # Size of the portion (x, y)
            }
            diffs.append(diff)

        return diffs
Exemple #32
0
def difference(img_a, img_b):
    """
    Calculates the difference between two images, defined as the sum of the
    variance of each color channel contained by the image resulting from their
    subtraction.
    """
    return sum(ImageStat.Stat(ImageChops.difference(img_a, img_b)).var)
Exemple #33
0
 def _dist(self, tile, reference_image):
     """ Calculates the distance of an image to a reference image"""
     reference_image = reference_image.resize(tile.size, Image.NEAREST)
     xor = ImageChops.difference(tile, reference_image).getcolors()
     for cnt, color in xor:
         if color == 255:
             return cnt
     return 0
 def compare_images(self, im1, im2):
     """
     Calculate the exact difference between two images.
     """
     im1 = Image.open(im1)
     im2 = Image.open(im2)
     if ImageChops.difference(im1, im2).getbbox() is not None:
         raise AssertionError("Image: %s is different from baseline: %s" % (im1.filename, im2.filename))
Exemple #35
0
def autocrop(img):
    """ Crop white borders from image. """
    bg = Image.new('1', img.size, 255)
    diff = ImageChops.difference(img, bg)
    bbox = diff.getbbox()
    if bbox:
        img = img.crop(bbox)
    return img
 def substract(self, inimage, orientation=5):
     """apply a substraction mask on the image"""
     self.img = inimage
     self.x, self.y = self.img.size
     ImageFile.MAXBLOCK = self.x * self.y
     self.mask(orientation)
     k = ImageChops.difference(self.img, self.bigsig)
     return k
Exemple #37
0
def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"
    diff = ImageChops.difference(im1, im2)
    h = diff.histogram()
    sq = (value * ((idx % 256)**2) for idx, value in enumerate(h))
    sum_of_squares = sum(sq)
    rms = math.sqrt(sum_of_squares / float(im1.size[0] * im1.size[1]))
    return rms
Exemple #38
0
 def recalc(self):
     if self._recalc == 1:
         diff = ImageChops.difference(self.img, self.reference_img)
         h = diff.histogram()
         sq = (value*(idx**2) for idx, value in enumerate(h))
         sum_of_squares = sum(sq)
         self.similarity = math.sqrt(sum_of_squares/float(self.img.size[0] * self.img.size[1]))
         self._recalc = 0
def getImgDiff(pic1, pic2):
    img1 = Image.fromarray(pic1)
    img2 = Image.fromarray(pic2)
    #img1.show()

    diff = ImageChops.difference(img1, img2)

    return diff
Exemple #40
0
def trim(image, border_color):
    mask = Image.new(image.mode, image.size, border_color)
    diff = ImageChops.difference(image, mask)
    bounds = diff.getbbox()
    if bounds:
        return image.crop(bounds)
    else:
        return None
Exemple #41
0
 def DoComparison(self, image1=None, image2=None):
     if not image1: image1 = self.image1
     if not image2: image2 = self.image2
     diffs = ImageChops.difference(image1, image2)
     return {
         "entropy": self.ImageEntropy(diffs),
         "img": image2
         }
Exemple #42
0
def operationGrafic(imA,imB):

    #imDest = ImageChops.multiply(imA, imB) 
    #imDest = ImageChops.difference(imA, imB) 
    #imDest = ImageChops.screen(imA, imB) 
    imDest = ImageChops.difference(imB, imA) 

    return imDest
Exemple #43
0
def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"
    diff = ImageChops.difference(im1, im2)
    h = diff.histogram()
    sq = (value * (idx ** 2) for idx, value in enumerate(h))
    sum_of_squares = sum(sq)
    rms = math.sqrt(sum_of_squares / float(im1.size[0] * im1.size[1]))
    return rms
 def calculate_rms_difference(self, im1, im2):
     """
     Calculate the root-mean-square difference between two images.
     If the images are exactly identical, the value is zero.
     """
     h = ImageChops.difference(im1, im2).histogram()
     # calculate rms
     return math.sqrt(reduce(operator.add, map(lambda h, i: h * (i ** 2), h, range(256))) / (float(im1.size[0]) * im1.size[1]))
def rmsdiff(im1, im2):
    "Calculate the root-mean-square difference between two images"

    h = ImageChops.difference(im1, im2).histogram()

    # calculate rms
    return math.sqrt(reduce(operator.add,
        map(lambda h, i: h*(i**2), h, range(256))) / (float(im1.size[0]) * im1.size[1]))
Exemple #46
0
    def do_difference(self):
        """usage: difference <image:pic1> <image:pic2>

        Pop the two top images, push the difference image
        """
        import ImageChops
        image1 = self.do_pop()
        image2 = self.do_pop()
        self.push(ImageChops.difference(image1, image2))
Exemple #47
0
def objectRecognize(dstImage, refImage, boundbox):
    #
    source = refImage.crop(boundbox)
    dest = dstImage.crop(boundbox)

    # Smooth operation
    source = source.filter(ImageFilter.SMOOTH)
    dest = dest.filter(ImageFilter.SMOOTH)

    # Get difference between source image and reference image
    imdiff = ImageChops.difference(source, dest)

    # Increase the contrast of the difference image
    enhancer = ImageEnhance.Contrast(imdiff)
    imdiff = enhancer.enhance(1.1)
    imdiff = imdiff.convert('1')

    # Get bounding box of the object
    box = imdiff.getbbox()
    # bound box of recognized object

    # Crop target object from the difference image
    recogObject = imdiff.crop(box)

    # Get global image statics
    objStat = ImageStat.Stat(recogObject)
    tarStat = ImageStat.Stat(imdiff)

    # Get object region and object pixels occupied
    cropPixel = objStat.count[0]
    objectPixel = objStat.sum[0]
    objectPixel = int(objectPixel) / 255

    totalPixel = tarStat.count[0]
    objectPixel2 = tarStat.sum[0]
    objectPixel2 = int(objectPixel2) / 255

    # Caculate object pixels percent
    if float(cropPixel) > 0.0 and float(totalPixel) > 0.0:
        percent = float(objectPixel) / float(cropPixel)
        percent2 = float(objectPixel2) / float(totalPixel)
    else:
        percent = 0
        percent = 0

    print percent
    print percent2

    if percent >= 0.05 and percent2 >= 0.0005:
        print "object detected\n"
        return True
    else:
        print "nothing detected\n"
        return False

    return percent
Exemple #48
0
    def equal(self, img1, img2):
        """Compares two screenshots.
        @param img1: screenshot to compare.
        @param img2: screenshot to compare.
        @return: equal status.
        """
        if not HAVE_PIL:
            return None

        return ImageChops.difference(img1, img2).getbbox() is None
Exemple #49
0
def isImagesIdentical(im1, im2):
    if im1.size[0] == 0 or im1.size[1] == 0:
        return False

    if im2.size[0] == 0 or im2.size[1] == 0:
        return False

    bbox = ImageChops.difference(im1, im2).getbbox()
    r = bbox is None
    return r
Exemple #50
0
    def _diff_png(self, ref_path, result_path):
        try:
            import Image, ImageChops
        except ImportError:
            raise NotImplementedError

        ref = Image.open(ref_path)
        result = Image.open(result_path)
        diff = ImageChops.difference(ref, result)
        diff.save(result_path + '.diff', 'png')
Exemple #51
0
 def assertEqualImages(self, fn1, fn2):
     if haveImageLibs:
         im1 = Image.open(fn1)
         im2 = Image.open(fn2)
         return ImageChops.difference(im1, im2).getbbox() is None
     else:
         warnings.warn(
             "**** IMPORT: Cannot import Image and/or ImageChops" +
             ", so Image comparisons in testAnalysis have been" +
             " disabled.")
         return True
Exemple #52
0
def main():
    '''Main Function'''

    url1 = raw_input('Enter the link to the first image: ')
    url2 = raw_input('Enter the link to the second image: ')

    ext1 = extension(url1)
    ext2 = extension(url2)

    if string.upper(ext1) != string.upper(ext2):
        print 'File-types dont match..!'
        sys.exit(1)

    file1 = 'im1' + ext1
    file2 = 'im2' + ext2

    urlretrieve(url1, file1)
    urlretrieve(url2, file2)

    diff_perc_seq = []

    im1 = Image.open(file1)
    im2 = Image.open(file2)

    im1, im2 = make_even(im1, im2)  #The image sizes are even now.

    diff_image = ImageChops.difference(
        im1,
        im2)  #diff_image contains the pixel level difference as an RGB tuple.

    #getbbox returns box containing the non-zero regions of the image. If its none, difference is none..!
    if diff_image.getbbox() is None:
        print 'Mirror Images..! The images are 100% similar. Similarity Scale value - 100'
    else:
        pixel_tuple_seq = diff_image.getdata(
        )  #pixel_tuple_seq contains the list of difference pixel tuples(R, G, B).

        pixel_rms_seq = map(
            rms, pixel_tuple_seq
        )  #pixel_rms_seq contains the rms list of difference pixel tuples.
        #The percentage of difference is found out using formula, perc = (value/255) * 100
        for item in pixel_rms_seq:
            diff_perc_seq.append(item / 255 * 100)
        avg_diff = sum(diff_perc_seq) / len(
            diff_perc_seq)  #The total average difference is found out.
        similarity = 100 - avg_diff

        if avg_diff == 100:
            print 'The images are completely dissimilar. Similarity scale value - 0'
        else:
            print 'The images are %.2f%% similar. Similarity scale value - %.2f ' % (
                similarity, similarity)
    os.system('rm ' + file1 + ' ' + file2)
Exemple #53
0
def PreProcess(im):
    im = NMode(im)
    im1 = ndimage.grey_erosion(im, size=(10, 10))
    scipy.misc.imsave("eroded.jpg", im1)
    im1 = Image.open("eroded.jpg")

    im = ImageOps.equalize(im, 0)
    im = ImageChops.difference(im1, im)
    #print ("image height %d and width %d\n"%(imh,imw))

    im = GBinarization(im)  #binarize the image
    return im
Exemple #54
0
    def compare(self, img1, img2):
        img = ImageChops.difference(img1, img2)
        xsize, ysize = img.size

        for s in range(0, xsize / 3):
            s = s * 3
            for m in range(0, ysize / 3):
                m = m * 3
                img.getpixel((s, m))
                if g > 150:
                    return True
        return False
Exemple #55
0
def background_crop(image_name, new_name, bgcolor):
    """ removes frame of bgcolor from and image and saves the image under new_name """
    print('background_crop:' + image_name)
    image = Image.open(image_name)
    bg = Image.new("RGBA", image.size, bgcolor)
    diff = ImageChops.difference(image, bg)
    bbox = diff.getbbox()

    if bbox:
        new_image = image.crop(bbox)
        new_image.save(new_name)
    return bbox
Exemple #56
0
 def cropify(self):
     """Crops output images"""
     print "crop images"
     # Oh we are back!
     for fpath in self._outpaths():
         print "\t%s" % fpath
         im = Image.open(fpath)
         im = im.convert("RGBA")
         bg = Image.new("RGBA", im.size, (255, 255, 255, 255))
         diff = ImageChops.difference(im, bg)
         bbox = diff.getbbox()
         im2 = im.crop(bbox)
         im2.save(fpath)
Exemple #57
0
 def cropImage(self, size):
     """ Cropping image method will crop image based on the provided new size
     @param size: the size of the new image
     @param type: tuple (width, height) 
     """
     if self.__im.mode == "P":
         self.__im = self.__im.convert("RGB")
     
     bgColor = (255, 255, 255)
     bg = Image.new("RGB", size, bgColor)
     diff = ImageChops.difference(self.__im, bg)
     bbox = diff.getbbox()
     if bbox:
         self.__im = self.__im.crop(bbox)
Exemple #58
0
def demo1():
    from PIL import Image
    import ImageChops

    path = "D:/code/image/image/"
    im1 = Image.open(path + "1.jpg")
    im2 = Image.open(path + "2.jpg")

    diff = ImageChops.difference(im2, im1)
    print diff

    im1.show()
    im2.show()
    diff.show()
Exemple #59
0
    def apply(self):
        keys = self._params.keys()
        if ('width' in keys or 'height' in keys) and not 'crop' in keys:
            if 'bgcolor' in keys:
                bgcolor = hex_to_color(self._params['bgcolor'])
            else:
                bgcolor = (255, 255, 255, 255)

            bg = Image.new(self._image.mode, self._image.size, bgcolor)
            diff = ImageChops.difference(self._image, bg)
            bbox = diff.getbbox()

            return self._image.crop(bbox)
        return self._image
Exemple #60
0
def root_mean_square_difference(im1, im2):
    try:

        diff = ImageChops.difference(
            im1, im2
        )  #Returns the absolute value of the difference between the two images
        h = diff.histogram()
        sq = (value * (idx**2) for idx, value in enumerate(h))
        sum_of_squares = sum(sq)
        rms = math.sqrt(sum_of_squares / float(im1.size[0] * im1.size[1]))
    except ValueError:
        return -1
    else:
        return rms