def calcutateHistogram(img): xValue = [0 for x in range(img.shape[0])] for j in range(img.shape[1]): for i in range(img.shape[0]): if img[j][i] == 255: xValue[i] += 1 plt.plot(xValue) plt.title("Histogram Of Binary Image") plt.xlabel("X Cordinate Value") plt.ylabel("Number Of White Pixel") plt.show() image = img.copy() image = cv2.cvtColor(image, cv2.COLOR_GRAY2RGB) cv2.line(image, (image.shape[0] // 2, 0), (image.shape[0] // 2, image.shape[1]), (0, 0, 255), 8) ImagePreProcessing.display(image, "Left And Right Lung Area", .25)
def test_dimensional_measurements_4(self): print("Testing measurements with sample 1200dpi") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(16, 1200, 'cm', image_path='../Images/1200dpi.jpg') # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 10.7992), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 6.3140), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 5.1075), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 3.1784), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 3.1662), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 27.3069), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 29.2833), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, 0.56596), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_3(self): print("Testing measurements with sample 1200dpi") ImagePreProcessing.TESTING = 1 new_img = Image_Enhancement.image_enhancement('../Images/1200dpi.jpg') image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(16, 1200, 'cm', image_path='../Images/1200dpi.jpg', enhanced_image= new_img) # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 10.8798), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 6.3172), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 5.1043), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 3.1533), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 3.1467), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 31.7354), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 34.4873), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, 0.74789), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_1(self): print("Testing measurements with sample 0.0.0") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y,\ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(16, 1200, 'cm', image_path='../Images/R_0.0.0.jpg', enhanced_image= None) # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 16.2273), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 6.6696), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 4.8683), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 3.2406), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 3.4100), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 25.9764), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 34.5381), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, -1.2249), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_2(self): print("Testing measurements with sample 1.1.1") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(16, 1800, 'in', image_path='../Images/R_1.1.1.jpg') # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 3.9020), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 2.9550), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 1.9560), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 1.4577), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 1.4416), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 2.3856), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 2.2770), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, 0.13438), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_7(self): print("Testing measurements with sample 4800dpi") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(12, 4800, 'cm', image_path='../Images/Sample2.tif') # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 10.8029), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 6.3156), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 5.1197), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 3.1696), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 3.1571), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 30.6929), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 33.1669), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, 0.64975), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_6(self): print("Testing measurements with sample 2400dpi") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(12, 2400, 'cm', image_path='../Images/2400dpi.bmp') # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 10.8251), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 6.3167), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 5.1197), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 3.1742), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 3.1610), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 29.3268), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 31.7996), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, 0.63259), 3.5, "Product of inertia calculation has more than 3.5% of error")
def test_dimensional_measurements_5(self): print("Testing measurements with sample 1.1.1.B2") ImagePreProcessing.TESTING = 1 image, binarized_image, area, outer_diameter, inner_diameter, centroid_x, centroid_y, moment_of_x, moment_of_y, \ moment_product, outer_measurements, inner_measurements = \ ImagePreProcessing.pre_process_image(12, 1800, 'in', image_path='../Images/1.11.B2.jpg') # Compare measurements with actual values self.assertLessEqual(calculate_error(area, 2.270), 3.5, "Area calculation has more than 3.5% of error") self.assertLessEqual(calculate_error(outer_diameter, 2.82), 3.5, "Outer diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(inner_diameter, 2.25), 3.5, "Inner diam. has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_x, 1.3825), 3.5, "Centroid X axis has more than 3.5% of error") self.assertLessEqual(calculate_error(centroid_y, 1.3893), 3.5, "Centroid Y axis has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_x, 1.4672), 3.5, "X-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_of_y, 1.6038), 3.5, "Y-axis moment calculation has more than 3.5% of error") self.assertLessEqual( calculate_error(moment_product, -0.08368), 3.5, "Product of inertia calculation has more than 3.5% of error")
def getRegionOfInterest(OrginalImage): PreProcessedImage = ImagePreProcessing.imagePreProcessing( OrginalImage.copy()) # LeftProcessedImage = calculateLeftLungArea(PreProcessedImage) # LeftBounbaryImage = findBorder(LeftProcessedImage) # LeftLungBorderPixel = getLeftLungBorderPixel(LeftBounbaryImage) ResizedPreProcessedImage = cv2.resize(PreProcessedImage, (1024, 1024), interpolation=cv2.INTER_AREA) OrginalImage = cv2.resize(OrginalImage, (1024, 1024), interpolation=cv2.INTER_AREA) BorederOfResizedImage = findBorder(ResizedPreProcessedImage) kernel = np.ones((5, 5), np.uint8) BorederOfResizedImage = cv2.dilate(BorederOfResizedImage, kernel, iterations=1) LeftLungBorderPixel = getLeftLungBorderPixel(BorederOfResizedImage) RightLungBorderPixel = getRightLungBorderPixel(BorederOfResizedImage) # ImagePreProcessing.display(BorederOfResizedImage, "Border", .5) ComparingImage = ResizedPreProcessedImage.copy() ResizedPreProcessedImage = cv2.cvtColor(ResizedPreProcessedImage, cv2.COLOR_GRAY2RGB) OrginalImage = cv2.cvtColor(OrginalImage, cv2.COLOR_BGR2GRAY) for i in range(len(LeftLungBorderPixel) - 1): cv2.circle(ResizedPreProcessedImage, (LeftLungBorderPixel[i][1], LeftLungBorderPixel[i][0]), 1, (0, 0, 255), 2) for i in range(len(RightLungBorderPixel) - 1): cv2.circle(ResizedPreProcessedImage, (RightLungBorderPixel[i][1], RightLungBorderPixel[i][0]), 1, (0, 0, 255), 2) # ImagePreProcessing.display(ResizedPreProcessedImage, "BorderImage", .5) ImageForSearch = [[255 for x in range(1024)] for y in range(1024)] NewImageForSearch = [[255 for x in range(1024)] for y in range(1024)] LeftLung = cv2.imread( LeftLungBorderPixel[len(LeftLungBorderPixel) - 1][0].replace("'", ""), cv2.IMREAD_GRAYSCALE) RightLung = cv2.imread( RightLungBorderPixel[len(RightLungBorderPixel) - 1][0].replace( "'", ""), cv2.IMREAD_GRAYSCALE) for i in range(ComparingImage.shape[0]): for j in range(ComparingImage.shape[1]): if ComparingImage[i][j] == 0 and LeftLung[i][j] == 255: ImageForSearch[i][j] = 0 NewImageForSearch[i][j] = NewImageForSearch[i][j] - \ OrginalImage[i][j] if ComparingImage[i][j] == 0 and RightLung[i][j] == 255: ImageForSearch[i][j] = 0 NewImageForSearch[i][j] = NewImageForSearch[i][j] - \ OrginalImage[i][j] ImageForSearch = calculateMeanStd(NewImageForSearch, ImageForSearch) # cv2.imwrite("Template.bmp",ImageForSearch) ImageForSearch = np.array(ImageForSearch) # img = Image.fromarray(ImageForSearch) cv2.imwrite("Template.bmp", ImageForSearch)
def test_file_creation(self): print("Testing file creation") # View if all files are being created in the respective directory ImagePreProcessing.pre_process_image( 16, 1200, 'cm', image_path='../Images/R_0.0.0.jpg') self.assertTrue(os.path.exists('Pre_Processing/binarized_image.jpg'), "Binarized image was not saved") self.assertTrue(os.path.exists('Pre_Processing/grayscale_image.jpg'), "Grayscale image was not saved") self.assertTrue( os.path.exists('Pre_Processing/binarized_bounded_image.jpg'), "Binarized bounded image was not saved") self.assertTrue(os.path.exists('Pre_Processing/bounded_image.jpg'), "Bounded input image was not saved") self.assertTrue(os.path.exists('Pre_Processing/centroid.jpg'), "Centroid image was not saved") self.assertTrue(os.path.exists('Pre_Processing/contour_image.jpg'), "Contoured input image was not saved") self.assertTrue(os.path.exists('Pre_Processing/filled_image.jpg'), "Filled image was not saved")
def DetectTable(): content = request.json download_url = "https://tableextractor.blob.core.windows.net/extracted-images/1557478921912_Page%2001.png" response = urllib.request.urlopen(download_url) txt=download_url.split('/') imageName=txt[len(txt)-1] file = open("ExtracedTables\\"+imageName, 'wb') file.write(response.read()) file.close() image=cv.imread("ExtracedTables\\"+imageName,1) imageCopy = image ippObj = ipp.ImagePreProcessing() image = ippObj.GammaAdujst(image) image = ippObj.Threshholding(image, 21) (contours, intersections) = ippObj.StructureExtraction(image,10) # Get tables from the images tables = [] # list of tables for i in range(len(contours)): (rect, table_joints) = tableutils.verify_table(contours[i],intersections) if rect == None or table_joints == None: continue # Create a new instance of a table table = TableStructure(rect[0], rect[1], rect[2], rect[3]) # Get an n-dimensional array of the coordinates of the table joints joint_coords = [] for i in range(len(table_joints)): joint_coords.append(table_joints[i][0][0]) joint_coords = np.asarray(joint_coords) # Returns indices of coordinates in sorted order # Sorts based on parameters (aka keys) starting from the last parameter, then second-to-last, etc sorted_indices = np.lexsort((joint_coords[:, 0],joint_coords[:, 1])) joint_coords = joint_coords[sorted_indices] # Store joint coordinates in the table instance table.set_joints(joint_coords) tables.append(table) te = TableExtraction() tables = te.tableSort(tables) images = te.ExtractTable(imageCopy, tables) cv.imwrite("ExtracedTables/"+imageName, images) result=te.StoreExtractedTable(images) return result
def ExtractTable(self, image, table): te = TableExtraction() ippObj = ipp.ImagePreProcessing() tableSize = len(table) (x1, x2) = te.setXValue(table, 0) (y1, y2) = te.setYValue(table, 0) print(tableSize) if tableSize == 2: (x1, x2) = te.setXValue(table, 1) y1 = y2 y2 = table[1].y + table[1].h elif tableSize > 2: x1 = min(table[tbl].x for tbl in range(1, len(table))) x2 = max(table[tbl].x + table[tbl].w for tbl in range(1,len(table))) y1 = y2 y2 = max(table[tbl].x + table[tbl].w for tbl in range(2,len(table))) images = ippObj.CropImage(image, x1, x2, y1, y2) print(type(images)) return images
def run(self): """ Start the process thread that will run the Sprout Controller that calls Image Enhancement Module, Image Pre-Processing Module, Region Extraction Module, and Fiber Density and Distribution Module. :return: None """ global step_enhanced_image, step_bounded_input_image, num_rings, num_wedges, bounded_binarized_input_image print("--------------------------------------------") print("Sprout Controller: Acquired Input Parameters") print("--------------------------------------------") # print user input for testing print("User input:") print(" img_path = " + self.in_data['img_path']) print(" intermediate_path = " + self.in_data['intermediate_path']) print(" units = " + self.in_data['units']) print(" num_measurement = " + str(self.in_data['num_measurement'])) print(" num_wedges = " + str(self.in_data['num_wedges'])) print(" num_rings = " + str(self.in_data['num_rings'])) print(" img_dpi = " + str(self.in_data['img_dpi'])) print(" enhance = " + str(self.in_data['enhance'])) print(" Pixel Map = " + str(self.in_data['pixelMap'])) time_start = time.time() # Create and change current working directory if not os.path.exists(self.in_data['intermediate_path']): try: os.makedirs(self.in_data['intermediate_path']) os.chdir(self.in_data['intermediate_path']) except OSError: self.sprout_ui.error_message = "Unable to create new intermediate path folder." self.sprout_ui.progressBar.setValue(2) return else: counter = 1 # Verify if this path exists, if it does exist add a number after file name and verify again. # Continue this loop, increasing the appended number, until the file path does not exist. try: new_path = self.in_data['intermediate_path'] + str(counter) while os.path.exists(new_path): new_path = self.in_data['intermediate_path'] + str(counter) counter += 1 print("New path " + new_path) os.makedirs(new_path) os.chdir(new_path) except Exception: self.sprout_ui.error_message = "Unable to create new intermediate path folder." self.sprout_ui.progressBar.setValue(2) return print("Current Working Directory:") print(" " + os.getcwd()) # To aid with simulation for get_fiber_density num_rings = self.in_data['num_rings'] num_wedges = self.in_data['num_wedges'] # Check if has an interrupt request (Stop Button Interrupt) if self.isInterruptionRequested(): return # If image enhancement is required run Image Enhancement Module if self.in_data['enhance']: try: step_enhanced_image = Image_Enhancement.image_enhancement( self.in_data['img_path']) except Exception as e: self.sprout_ui.error_message = "Error in Image Enhancement:\n " + str( e) self.sprout_ui.progressBar.setValue(2) return self.update_progress_bar(self.p_img_enhancement_percent) else: step_enhanced_image = None # Check if has an interrupt request (Stop Button Interrupt) if self.isInterruptionRequested(): return # Run Image Pre-processing Module try: bounded_binarized_input_image, step_bounded_input_image, = ImagePreProcessing.pre_process_image( self.in_data['num_measurement'], self.in_data['img_dpi'], self.in_data['units'], self.in_data['img_path'], step_enhanced_image, self, self.in_data['pixelMap']) except Exception as e: self.sprout_ui.error_message = "Error in Image Pre-processing:\n " + str( e) self.sprout_ui.progressBar.setValue(2) return # Check if has an interrupt request (Stop Button Interrupt) if self.isInterruptionRequested(): return # Run Region Extraction Module try: region_dictionary = Region_Extraction.region_extraction( step_bounded_input_image, bounded_binarized_input_image, self.in_data['num_wedges'], self.in_data['num_rings'], self) except Exception as e: self.sprout_ui.error_message = "Error in Region Extraction:\n " + str( e) self.sprout_ui.progressBar.setValue(2) return # Check if has an interrupt request (Stop Button Interrupt) if self.isInterruptionRequested(): return # Run Fiber Density and Distribution Module try: Fiber_Density_Calculation.fiber_density_and_distribution( self.in_data['num_rings'], self.in_data['num_wedges'], region_dictionary) except Exception as e: self.sprout_ui.error_message = "Error in Fiber Density and Distribution:\n " + str( e) self.sprout_ui.progressBar.setValue(2) return self.update_progress_bar(self.p_fiber_density_and_distribution) print("\n * Sprout Controller: Finished Successfully * ") print(" Total time: " + str(time.time() - time_start) + " sec") print(" Equal to: " + str((time.time() - time_start) / 60) + " min") return
def run(self): """ Start the process thread that will run the Sprout Controller that calls Image Enhancement Moduel, Image Pre-Processing Module, Region Extraction Module, and Fiber Density and Distribution Moduel. :return: None """ global step_enhanced_image, step_bounded_input_image, num_rings, num_wedges print("--------------------------------------------") print("Sprout Controller: Acquired Input Parameters") print("--------------------------------------------") # print user input for testing print("User input:") print(" img_path = " + self.in_data['img_path']) print(" intermediate_path = " + self.in_data['intermediate_path']) print(" units = " + self.in_data['units']) print(" num_measurement = " + str(self.in_data['num_measurement'])) print(" num_wedges = " + str(self.in_data['num_wedges'])) print(" num_rings = " + str(self.in_data['num_rings'])) print(" img_dpi = " + str(self.in_data['img_dpi'])) print(" enhance = " + str(self.in_data['enhance'])) if not os.path.exists(self.in_data['intermediate_path']): try: os.makedirs(self.in_data['intermediate_path']) except: raise Exception("Unable to create intermediate path folder") os.chdir(self.in_data['intermediate_path']) print("Current Working Directory:") print(" " + os.getcwd()) # To aid with simulation for get_fiber_density num_rings = self.in_data['num_rings'] num_wedges = self.in_data['num_wedges'] # If image enhancement is required run Image Enhancement Module if self.in_data['enhance']: try: step_enhanced_image = Image_Enhancement.image_enhancement( self.in_data['img_path']) except Exception as e: print("Error in Image Enhancement:\n " + str(e)) return self.update_progress_bar() # Run Image Pre-processing Module try: bounded_binarized_input_image, step_bounded_input_image, = ImagePreProcessing.pre_process_image( self.in_data['num_measurement'], self.in_data['img_dpi'], self.in_data['units'], self.in_data['img_path'], step_enhanced_image) process = psutil.Process(os.getpid()) print(process.memory_info().rss / 1000000, "MB") except Exception as e: print("Error in Image Pre-processing:\n " + str(e)) return self.update_progress_bar() # Run Region Extraction Module dictionary = Region_Extraction.region_extraction( step_bounded_input_image, bounded_binarized_input_image, self.in_data['num_wedges'], self.in_data['num_rings']) self.update_progress_bar() # Run Fiber Density and Distribution Module try: Fiber_Density_Calculation.fiber_density_and_distribution( self.in_data['num_rings'], self.in_data['num_wedges'], dictionary) except Exception as e: print("Error in Fiber Density and Distribution:\n " + str(e)) return self.update_progress_bar() print("\n * Sprout Controller: Finished Successfully * ") return