def test_jpg_reencode_diff(self): # when a png is converted two jpeg two times to a different file with the same encoder # diff is 0 self.assertEqual(imgcompare.image_diff_percent(JPG_CAT, JPG_CAT_DIFFERENT_RUN), 0) # when reencoding the same jpg again, a minimal diff is found self.assertLess(imgcompare.image_diff_percent(JPG_CAT, JPG_CAT_REENCODED), 0.015)
def test_thresholds(self): self.assertEqual(0, imgcompare.image_diff_percent(JPG_BLACK, JPG_BLACK)) self.assertEqual(100, imgcompare.image_diff_percent(JPG_BLACK, JPG_WHITE)) self.assertEqual(50, imgcompare.image_diff_percent(JPG_BLACK, JPG_HALF_BW))
def test_minimal_image_diff(self): # small changes on the image result in a bigger diff than jpg reencode self.assertEqual(round(imgcompare.image_diff_percent(JPG_CAT, JPG_CAT_SLIGHT_DIFF), 2), 0.34) self.assertEqual(round(imgcompare.image_diff_percent(PNG_CAT, PNG_CAT_SLIGHT_DIFF), 2), 0.28) # diffing jpg with png results in a lot different results self.assertEqual(round(imgcompare.image_diff_percent(JPG_CAT, PNG_CAT_SLIGHT_DIFF), 2), 15.96) self.assertEqual(round(imgcompare.image_diff_percent(PNG_CAT_SLIGHT_DIFF, JPG_CAT), 2), 15.96)
def test_half_black(self): self.assertEqual(imgcompare.image_diff_percent(PNG_HALF_BW, PNG_BLACK), 50) self.assertEqual(imgcompare.image_diff_percent(PNG_HALF_BW, PNG_WHITE), 50) self.assertEqual(imgcompare.image_diff_percent(PNG_BLACK, PNG_HALF_BW), 50) self.assertEqual(imgcompare.image_diff_percent(PNG_WHITE, PNG_HALF_BW), 50) self.assertEqual(imgcompare.image_diff_percent(JPG_HALF_BW, JPG_BLACK), 50) self.assertEqual(imgcompare.image_diff_percent(JPG_HALF_BW, JPG_WHITE), 50) self.assertEqual(imgcompare.image_diff_percent(JPG_BLACK, JPG_HALF_BW), 50) self.assertEqual(imgcompare.image_diff_percent(JPG_WHITE, JPG_HALF_BW), 50)
def load_labels(): fila = 1 for img1 in os.listdir(DIR): for img2 in os.listdir(DIR): #Obteniendo el porcentaje de diferencia url1 = 'C:/Users/EGH/PycharmProjects/Ouch/train/' + img1 url2 = 'C:/Users/EGH/PycharmProjects/Ouch/train/' + img2 percentage = image_diff_percent(url1, url2) data.loc[fila, [str(img2)]] = percentage #print('Imprimiendo coordenadas de fila: ' + str(fila) + ' columna: ' + str(img2) + ' porcentage de diferencia: ' + str(data.loc[fila, [str(img2)]])) fila = fila + 1 print('Imprimiendo coordenadas de fila: ' + str(fila))
def test_black_white_image_diff(self): self.assertEqual(round(imgcompare.image_diff_percent(JPG_CAT, JPG_BLACK), 2), 27.58) self.assertEqual(round(imgcompare.image_diff_percent(JPG_CAT, JPG_WHITE), 2), 72.07) self.assertEqual(round(imgcompare.image_diff_percent(JPG_CAT, JPG_HALF_BW), 2), 55.15) self.assertEqual(round(imgcompare.image_diff_percent(PNG_CAT, PNG_BLACK_RGB), 2), 11.63) self.assertEqual(round(imgcompare.image_diff_percent(PNG_CAT, PNG_WHITE_RGB), 2), 88.04) self.assertEqual(round(imgcompare.image_diff_percent(PNG_CAT, PNG_HALF_BW_RGB), 2), 53.46)
def is_equal_with_tolerance(image1, image2, tolerance=Var.current("tolerance")): with allure.step("Comparing two images with tolerance: " + tolerance): image1_path = Img.root_path() + "/Data/Images/" + image1 image2_path = Img.root_path() + "/reports/images/" + image2 result = imgcompare.is_equal(image1_path, image2_path, tolerance=tolerance) allure.attach.file(image1_path, name=image1, attachment_type=allure.attachment_type.PNG) allure.attach.file(image2_path, name=image2, attachment_type=allure.attachment_type.PNG) if not result: if Var.env("snap") == "1": with allure.step("Copying the response file to the source file"): Img.copy_image(image2_path, image1_path) with allure.step("Attaching the diff image file"): image_diff_percent = imgcompare.image_diff_percent(image1_path, image2_path) allure.step("Difference Percentage for comparing images is" + image_diff_percent) diff_img_name = "diff_" + image1 + image2 + ".png" diff_img_path = Img.root_path() + "/reports/images/" + diff_img_name diffimg.diff(image1_path, image2_path, delete_diff_file=False, diff_img_file=diff_img_path, ignore_alpha=False) allure.attach.file(diff_img_path, name=diff_img_name, attachment_type=allure.attachment_type.PNG) assert (result is True), "Compared images are not equal even with tolerance"
def compare_file(): # download new image req.urlretrieve(img_url, "tmp/new_image.jpg") # check if previous image exists if os.path.isfile('tmp/old_image.jpg'): # previous file exists, compare old and new pictures img_comp_percentage = imgcompare.image_diff_percent( "tmp/old_image.jpg", "tmp/new_image.jpg") cloud_logger.debug("Img compare result: " + str(round(img_comp_percentage, 3)) + " (expected: " + str(IMG_COMP_RESULT) + ")") print("Img compare result: " + str(round(img_comp_percentage, 3)) + " (expected: " + str(IMG_COMP_RESULT) + ")") else: # previous file does not exist, comparison will be with next run of the job cloud_logger.debug("Previous version of image does not exist.") img_comp_percentage = 0 return round(img_comp_percentage, 1)
def test_black_white_image_diff(self): self.assertEqual( 27.75, round(imgcompare.image_diff_percent(JPG_CAT, JPG_BLACK), 2)) self.assertEqual( 72.25, round(imgcompare.image_diff_percent(JPG_CAT, JPG_WHITE), 2)) self.assertEqual( 55.32, round(imgcompare.image_diff_percent(JPG_CAT, JPG_HALF_BW), 2)) self.assertEqual( 11.79, round(imgcompare.image_diff_percent(PNG_CAT, PNG_BLACK_RGB), 2)) self.assertEqual( 88.21, round(imgcompare.image_diff_percent(PNG_CAT, PNG_WHITE_RGB), 2)) self.assertEqual( 53.62, round(imgcompare.image_diff_percent(PNG_CAT, PNG_HALF_BW_RGB), 2))
def is_equal(image1, image2): with allure.step("Comparing two images"): try: image1_path = Img.root_path() + "/Data/Images/" + image1 + ".png" image2_path = Img.root_path() + "/reports/images/" + image2 + ".png" result = imgcompare.is_equal(image1_path, image2_path) allure.attach.file(image1_path, name=image1, attachment_type=allure.attachment_type.PNG) allure.attach.file(image2_path, name=image2, attachment_type=allure.attachment_type.PNG) except Exception as e: allure.step("Exception happened while comparing the image: " + str(e)) result = False if not result: if Var.env("snap") == "1": with allure.step("Copying the response file to the source file"): Img.copy_image(image1_path, image2_path) with allure.step("Attaching the diff image file"): image_diff_percent = imgcompare.image_diff_percent(image1_path, image2_path) allure.step("Difference Percentage for comparing images is" + str(image_diff_percent)) diff_img_name = "diff_" + image1 + image2 + ".png" diff_img_path = Img.root_path() + "/reports/images/" + diff_img_name diffimg.diff(image1_path, image2_path, delete_diff_file=False, diff_img_file=diff_img_path, ignore_alpha=False) allure.attach.file(diff_img_path, name=diff_img_name, attachment_type=allure.attachment_type.PNG) assert (result is True), "Compared images are not equal"
def plotTest(self, directory, currentfile, bounding, subpathing, binpathing, framerate): global fps global threshold global binText fps = framerate x = [] y = [] afflictFile = open(directory + "/" + str(fps) + "FPS AfflictData.csv", "w+") afflictFile.write("Time(M),%Change, Af-Area(mm^2)\n") imi = str(subpathing) + "/isframe0.jpg" imiread = cv2.imread(imi) imireadGrayscale = cv2.cvtColor(imiread, cv2.COLOR_BGR2GRAY) retval, binarizedimi = cv2.threshold(imireadGrayscale, 75, 255, cv2.THRESH_BINARY) # +cv2.THRESH_OTSU) cv2.imwrite(str(binpathing) + "/binarizedimi0.jpg", binarizedimi) binarizedimipath = str(binpathing) + "/binarizedimi0.jpg" w = 0 for i in range(bounding): if testCancelled: return -1 im = str(subpathing) + "/isframe" + str(i) + ".jpg" # print("Frame difference with initial " + str(i + 1)) imread = cv2.imread(im) imreadGrayscale = cv2.cvtColor(imread, cv2.COLOR_BGR2GRAY) retval, binarizedim = cv2.threshold(imreadGrayscale, 75, 255, cv2.THRESH_BINARY) # +cv2.THRESH_OTSU) cv2.imwrite(str(binpathing) + "/binarizedim" + str(i) + ".jpg", binarizedim) binarizedimpath = str(binpathing) + "/binarizedim" + str(i) + ".jpg" percent = imgcmp.image_diff_percent(binarizedimpath, binarizedimipath) # print("Percent of afflicted pixels in subtract: " + str(percent)) x.append((i / (fps)) / 60) # points on xaxis########################################## afflictFile.write(str((i / (fps)) / 60) + ",") ######################################### if percent >= threshold: y.append(percent) afflictFile.write(str(percent) + "," + str(percent / 100.0 * 0.485) + "\n") binText.append("%Affliction between Initial and Frame " + str(i + 1) + ":\n - " + str(percent) + " - Appended Percent\n\n") # printing if frame has been read self.consoleTableBin.configure(state="normal") self.consoleTableBin.insert(tk.INSERT, binText[i]) self.consoleTableBin.see(tk.END) self.consoleTableBin.configure(state="disabled") self.programLoadingBar['value'] += 1 self.programLoadingBar.update() self.update_idletasks() self.update() # print("Appended percent.") if w == 0: w = percent x[i] -= w else: y.append(0) afflictFile.write("0,0\n") binText.append("%Affliction between Initial and Frame " + str(i + 1) + ":\n - " + str(percent) + " - Appended Zero\n\n") self.consoleTableBin.configure(state="normal") self.consoleTableBin.insert(tk.INSERT, binText[i]) self.consoleTableBin.see(tk.END) self.consoleTableBin.configure(state="disabled") self.update_idletasks() self.update() afflictFile.close() # plt.plot(x, y) # plt.xlabel('Time (secs)')#.1,.2,.3,etc. # plt.ylabel('% area covered') # plt.axis([0, bounding/10, 0, 0.5]) # plt.show() current = currentfile self.data1x = x self.data1y = y # root = tkinter.Tk() # root.wm_title("Embedding in Tk") # This is oneeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee # self.fig = Figure(figsize=(7, 6), dpi=100) # self.fig.add_subplot(111).plot(data1x, data1y) # axes = self.fig.get_axes() # ax1 = axes[0] self.fig, ax1 = plt.subplots() ax1.set_title("% Area Change vs Current vs Time", fontweight='bold') green = 'tab:green' ax1.set_xlabel('Time (Min)', fontweight='bold', labelpad=10) ax1.set_ylabel('% Area Covered', color=green, fontweight='bold', labelpad=10) ax1.plot(self.data1x, self.data1y, color=green) ax1.tick_params(axis='y', labelcolor=green, color=green) for tick in ax1.xaxis.get_major_ticks(): tick.label1.set_fontweight('bold') for tick in ax1.yaxis.get_major_ticks(): tick.label1.set_fontweight('bold') ax2 = ax1.twinx() self.data2x = [] self.data2y = [] with open(current) as f: reader = csv.reader(f, delimiter=',', quotechar='"') for row in reader: try: self.data2x.append(float(row[0])) except: pass try: self.data2y.append(float(row[1]) * 1000000) except: pass blue = 'tab:blue' ax2.set_ylabel('Current (μA)', color=blue, fontweight='bold', labelpad=10) # we already handled the x-label with ax1 ax2.plot(self.data2x, self.data2y, color=blue) ax2.tick_params(axis='y', labelcolor=blue, color=blue) for tick in ax2.yaxis.get_major_ticks(): tick.label2.set_fontweight('bold') for tick in ax2.xaxis.get_major_ticks(): tick.label2.set_fontweight('bold') # ax2.set_aspect(1.5) self.fig.set_dpi(150) self.fig.tight_layout() tend1 = time.time() # plt.show() plt.savefig(directory + "/" + str(fps) + " Graph.jpg") # plt.grid() # plt.gcf().canvas.draw() # self.fig = plt.figure() # plt.axvline(x=20) self.canvas = FigureCanvasTkAgg(self.fig, master=self.FGraph) # A tk.DrawingArea. self.canvas.draw() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) # self.fig.canvas.callbacks.connect('button_press_event', self.on_click) self.fig.canvas.callbacks.connect('button_release_event', self.on_click) # self.fig.canvas.callbacks.connect('motion_notify_event', self.on_click) self.currentLocationLine, v = plt.plot(0, 0, min(self.data2y), max(self.data2y), color='red', linewidth=2) toolbar = NavigationToolbar2Tk(self.canvas, self.FGraph) toolbar.update() self.canvas.get_tk_widget().pack(side=tk.TOP, fill=tk.BOTH, expand=1) if showingGraph: self.showOrHideGraph() self.showOrHideGraph() else: self.showOrHideGraph() return tend1
for i in range(5, 0, -1): time.sleep(1) print(i) x = mouse.position print("coloca el cursor en el segundo punto") for i in range(5, 0, -1): time.sleep(1) print(i) y = mouse.position coord = x + y now = datetime.now() im1 = ImageGrab.grab(bbox=(coord)) im1.save('primera.png', 'PNG') n = 0 while True: time.sleep(2) im2 = ImageGrab.grab(bbox=(coord)) percentage = imgcompare.image_diff_percent(im1, im2) print(percentage) if percentage < 1: print('igual') else: print('diferente') im2_name = now.strftime("%Y%m%d_") im2.save(img_path + im2_name + str(n) + '.png', 'PNG') n = n + 1 im1 = im2
def test_thresholds(self): self.assertEqual(imgcompare.image_diff_percent(JPG_BLACK, JPG_BLACK), 0) self.assertEqual(imgcompare.image_diff_percent(JPG_BLACK, JPG_WHITE), 100) self.assertEqual(imgcompare.image_diff_percent(JPG_BLACK, JPG_HALF_BW), 50)
def plotTest(directory, currentfile, bounding, subpathing, binpathing, framerate): global fps fps = framerate x = [] y = [] afflictFile = open(directory + "/" + str(fps) + "FPS AfflictData.csv", "w+") afflictFile.write("Time(M),%Change, Af-Area(mm^2)\n") imi = str(subpathing) + "/isframe0.jpg" imiread = cv2.imread(imi) imireadGrayscale = cv2.cvtColor(imiread, cv2.COLOR_BGR2GRAY) retval, binarizedimi = cv2.threshold(imireadGrayscale, 75, 255, cv2.THRESH_BINARY) #+cv2.THRESH_OTSU) cv2.imwrite(str(binpathing) + "/binarizedimi0.jpg", binarizedimi) binarizedimipath = str(binpathing) + "/binarizedimi0.jpg" w = 0 for i in range(bounding): im = str(subpathing) + "/isframe" + str(i) + ".jpg" print("Frame difference with initial " + str(i + 1)) imread = cv2.imread(im) imreadGrayscale = cv2.cvtColor(imread, cv2.COLOR_BGR2GRAY) retval, binarizedim = cv2.threshold( imreadGrayscale, 75, 255, cv2.THRESH_BINARY) #+cv2.THRESH_OTSU) cv2.imwrite( str(binpathing) + "/binarizedim" + str(i) + ".jpg", binarizedim) binarizedimpath = str(binpathing) + "/binarizedim" + str(i) + ".jpg" percent = imgcmp.image_diff_percent(binarizedimpath, binarizedimipath) print("Percent of afflicted pixels in subtract: " + str(percent)) x.append( (i / (fps)) / 60) # points on xaxis########################################## afflictFile.write(str( (i / (fps)) / 60) + ",") ######################################### if percent >= threshold: y.append(percent) afflictFile.write( str(percent) + "," + str(percent / 100.0 * 0.485) + "\n") print("Appended percent.") if w == 0: w = percent x[i] -= w else: y.append(0) afflictFile.write("0,0\n") print("Appended 0.") afflictFile.close() ## plt.plot(x, y) ## plt.xlabel('Time (secs)')#.1,.2,.3,etc. ## plt.ylabel('% area covered') ## plt.axis([0, bounding/10, 0, 0.5]) ## plt.show() current = currentfile data1x = x data1y = y fig, ax1 = plt.subplots() ax1.set_title("% Area Change vs Current vs Time", fontweight='bold') red = 'tab:red' ax1.set_xlabel('Time (Min)', fontweight='bold', labelpad=10) ax1.set_ylabel('% Area Covered', color=red, fontweight='bold', labelpad=10) ax1.plot(data1x, data1y, color=red) ax1.tick_params(axis='y', labelcolor=red, color=red) for tick in ax1.xaxis.get_major_ticks(): tick.label1.set_fontweight('bold') for tick in ax1.yaxis.get_major_ticks(): tick.label1.set_fontweight('bold') ax2 = ax1.twinx() data2x = [] data2y = [] with open(current) as f: reader = csv.reader(f, delimiter=',', quotechar='"') for row in reader: try: data2x.append(float(row[0])) except: pass try: data2y.append(float(row[1]) * 1000000) except: pass blue = 'tab:blue' ax2.set_ylabel('Current (μA)', color=blue, fontweight='bold', labelpad=10) # we already handled the x-label with ax1 ax2.plot(data2x, data2y, color=blue) ax2.tick_params(axis='y', labelcolor=blue, color=blue) for tick in ax2.yaxis.get_major_ticks(): tick.label2.set_fontweight('bold') for tick in ax2.xaxis.get_major_ticks(): tick.label2.set_fontweight('bold') fig.tight_layout() tend1 = time.time() # plt.show() plt.savefig(directory + "/" + str(fps) + " Graph.jpg") return tend1
def test_red_green_blue(self): self.assertEqual( 23.4, round( imgcompare.image_diff_percent(JPG_RED_GREEN_BLUE, JPG_RED_GREEN_GREEN), 2))
def test_cat_fox(self): self.assertEqual( 23.45, round(imgcompare.image_diff_percent(JPG_CAT, JPG_FOX), 2)) self.assertEqual( 23.45, round(imgcompare.image_diff_percent(JPG_FOX, JPG_CAT), 2))
def test_png_jpg_black_white(self): # to compare 'l' png with jpg, it has to be converted to RGB self.assertEqual( 0, imgcompare.image_diff_percent(PNG_BLACK_RGB, JPG_BLACK)) self.assertEqual( 0, imgcompare.image_diff_percent(PNG_WHITE_RGB, JPG_WHITE))