def mix_brock(): img_src1 = cv.imread("./img/1.png", 1) img_src2 = cv.imread("./img/2.png", 1) img_src3 = cv.imread("./img/3.png", 1) try: pal = cv.getTrackbarPos('hoge', winName) except: pal = 150 img_ave = img_src1 * (1 / 3) + img_src2 * (1 / 3) + img_src3 * ( 1 / 3) + pal - 150 cv.imwrite("./img/mix.png", img_ave) img = Image.open('./img/mix.png') to_pil(cca.grey_world(from_pil(to_pil(cca.stretch( from_pil(img)))))).save('./img/block.png') try: pal2 = cv.getTrackbarPos('hige', winName) except: pal2 = 0 if pal2 == 0: to_pil(cca.grey_world(from_pil(to_pil(cca.stretch( from_pil(img)))))).save('./img/block.png') elif pal2 == 1: to_pil(cca.retinex_with_adjust(cca.retinex( from_pil(img)))).save('./img/block.png') elif pal2 == 2: to_pil(cca.stretch(from_pil(img))).save('./img/block.png')
def applyEffectsACE_RETINEX(count, filename, file): print("{0} > apply ACE/RETINEX em {1}".format(count, filename)) chaveF = filename[28:36] nomeParaSalvar = pastaSaida + chaveF + '_' + file img = Image.open(filename) img = to_pil(cca.automatic_color_equalization(from_pil(img))) img = to_pil(cca.retinex(from_pil(img))) img.save(nomeParaSalvar)
def gw_stretch_eq(self, img): # convert to pil format img_pil = self.opencv_to_pil(img) img_gw_pil = to_pil(cca.grey_world(from_pil(img_pil))) img_gw_stretch_pil = to_pil(cca.stretch(from_pil(img_gw_pil))) img_gw_stretch_opencv = cv2.cvtColor(np.array(img_gw_stretch_pil), cv2.COLOR_RGB2BGR) return img_gw_stretch_opencv
def autoWhiteBalance(fl_input, fl_output, method = "automatic"): print("imageProcessing::autoWhiteBalance(fl_input, fl_output, method = 'automatic'") try: # Open the image object to be adjusted. img_pil_input = Image.open(fl_input) # Define the empty image object. img_pil_adj = None if method == "stretch": img_pil_adj = to_pil(cca.stretch(from_pil(img_pil_input))) elif method == "gray_world": img_pil_adj = to_pil(cca.gray_world(from_pil(img_pil_input))) elif method == "max_white": img_pil_adj = to_pil(cca.max_white(from_pil(img_pil_input))) elif method == "retinex": img_pil_adj = to_pil(cca.cca.retinex(from_pil(img_pil_input))) elif method == "retinex_adjusted": img_pil_adj = to_pil(cca.retinex_with_adjust(from_pil(img_pil_input))) elif method == "stdev_luminance": img_pil_adj = to_pil(cca.standard_deviation_and_luminance_weighted_gray_world(from_pil(img_pil_input))) elif method == "stdev_grey_world": img_pil_adj = to_pil(cca.standard_deviation_weighted_grey_world(from_pil(img_pil_input))) elif method == "luminance_weighted": img_pil_adj = to_pil(cca.luminance_weighted_gray_world(from_pil(img_pil_input))) elif method == "automatic": img_pil_adj = to_pil(cca.automatic_color_equalization(from_pil(img_pil_input))) # Save the adjusted image. img_pil_adj.save(fl_output) # Return the output file name. return(fl_output) except Exception as e: print("Error occured in imageProcessing::autoWhiteBalance(fl_input, fl_output, method = 'automatic'") print(str(e)) error.ErrorMessageImageProcessing(details=str(e), show=True, language="en") return(None)
def retinex_eq(self, img): # convert to pil format img_pil = self.opencv_to_pil(img) img_ret_pil = to_pil(cca.retinex(from_pil(img_pil))) img_ret_opencv = cv2.cvtColor(np.array(img_ret_pil), cv2.COLOR_RGB2BGR) return img_ret_opencv
def max_white_eq(self, img): # convert to pil format img_pil = self.opencv_to_pil(img) img_max_white_pil = to_pil(cca.max_white(from_pil(img_pil))) img_max_white__opencv = cv2.cvtColor(np.array(img_max_white_pil), cv2.COLOR_RGB2BGR) return img_max_white__opencv
def equalize_colors(input_path, method_name, on_condor=False): if not on_condor: yes_should_continue = query_yes_no( "All the images in %s will be modified.\n" "No backup will be created, ARE YOU SURE?" % input_path, default="no") if not yes_should_continue: print("End of game. No file has been edited.") return equalize_image = methods[method_name] filenames = os.listdir(input_path) progress_bar = None if not on_condor: progress_bar = progressbar.ProgressBarWithMessage(len(filenames), " Processing images") files_counter = 0 for filename in filenames: print (filename) file_path = os.path.join(input_path, filename) try: image = Image.open(file_path) except: print("Failed to open image %s, skipping." % file_path) continue new_image = to_pil(equalize_image(from_pil(image))) new_image.save(file_path) files_counter += 1 if progress_bar: progress_bar.update(files_counter) else: # on condor f = open(file_path + ".done", "w") f.writelines("test\n") f.close() # end of "for each image in the folder" if progress_bar: progress_bar.finish() print("%i images inside %s have been equalized" % (files_counter, input_path)) return
def equalize_colors(input_path, method_name, on_condor=False): if not on_condor: yes_should_continue = query_yes_no( "All the images in %s will be modified.\n" "No backup will be created, ARE YOU SURE?" % input_path, default="no") if not yes_should_continue: print("End of game. No file has been edited.") return equalize_image = methods[method_name] filenames = os.listdir(input_path) progress_bar = None if not on_condor: progress_bar = progressbar.ProgressBarWithMessage( len(filenames), " Processing images") files_counter = 0 for filename in filenames: print(filename) file_path = os.path.join(input_path, filename) try: image = Image.open(file_path) except: print("Failed to open image %s, skipping." % file_path) continue new_image = to_pil(equalize_image(from_pil(image))) new_image.save(file_path) files_counter += 1 if progress_bar: progress_bar.update(files_counter) else: # on condor f = open(file_path + ".done", "w") f.writelines("test\n") f.close() # end of "for each image in the folder" if progress_bar: progress_bar.finish() print("%i images inside %s have been equalized" % (files_counter, input_path)) return
def color_balance(self, imgLabel, n_algorithm, image, displayed_image): # Check if images exists if not self.__images_exists(): return # Choose algorithm and save original image orig_image = copy.deepcopy(image) if n_algorithm == 0: image.paste(ccu.to_pil(cca.max_white(ccu.from_pil(image)))) elif n_algorithm == 1: image.paste(ccu.to_pil(cca.grey_world(ccu.from_pil(image)))) elif n_algorithm == 2: image.paste( ccu.to_pil( cca.automatic_color_equalization(ccu.from_pil(image)))) self.__paste_image__(image, displayed_image, imgLabel) answer = tk.messagebox.askyesno("Changes prompt", "Apply changes?") # If no, restore image if not answer: image.paste(orig_image.copy()) self.__paste_image__(image, displayed_image, imgLabel)
def photo_callback(tipo): num = str(int(random.random()*100000)) #Camara: camera = picamera.PiCamera() camera.resolution = (512, 384) camera.brightness = 60 #camera.rotation = 90 camera.framerate = 10 #camera.contrast = 70 camera.exposure_mode ="auto" camera.awb_mode = "auto" #camera.awb_mode='fluorescent' if (tipo == 1): # camera.image_effect = 'colorbalance' print ("colorbalance") else: camera.image_effect = 'watercolor' GPIO.output(LedFlash, 1) camera.capture("../ImgCapture/image"+num+".bmp") GPIO.output(LedFlash, 0) camera.close() # Linea Vacia. printer.feed(1) imagen = Image.open("../ImgCapture/image"+num+".bmp") if (len(imagen.histogram())<400): setLed(True, False, False) printer.print("Error Campture Foto.") time.sleep(4) return # Cambiamos tamano imagen = imagen.resize(size, Image.ANTIALIAS) imagen = imagen.convert('L', dither=0) imagen = to_pil(cca.max_white(from_pil(imagen))) # https://github.com/shunsukeaihara/colorcorrect imagen.save("../ImgCorrect/image"+num+".bmp") # Convertimos en blancos y negros. imagen = imagen.convert('1', dither=1) # Giramos imagen = imagen.transpose(2) imagen.save("../ImgPrint/image"+num+".bmp") #Imprimimos!! printer.printImage(imagen, True) printer.feed(6) time.sleep(0.2) printer.feed(1)
def color_correct(args): in_dir = args.in_dir out_dir = args.out_dir if not os.path.exists(in_dir): raise Exception('{} does not exists.'.format(in_dir)) if not os.path.exists(out_dir): os.makedirs(out_dir) files = os.listdir(in_dir) grey_world = cca.grey_world if args.grey_world else lambda x: x stretch = cca.stretch if args.stretch else lambda x: x max_white = cca.max_white if args.max_white else lambda x: x for file in tqdm(files): image = Image.open(os.path.join(in_dir, file)) try: image = to_pil(stretch(max_white(grey_world(from_pil(image))))) except: print(file) pass image.save(os.path.join(out_dir, file))
def equalize_colors_file(input_file, method_name, on_condor=False): equalize_image = methods[method_name] print(input_file) try: image = Image.open(input_file) except: print("Failed to open image %s, skipping." % input_file) new_image = to_pil(equalize_image(from_pil(image))) new_image.save(input_file) if on_condor: f = open(input_file + ".done", "w") f.writelines("test\n") f.close() # end of "for each image in the folder" return
def extract_and_save_features(path_to_tiles, path_to_save_features): """Extract ResNet features from tile images. """ model = ResNet50(weights='imagenet', include_top=True) model = Model(inputs=model.inputs, outputs=model.get_layer('avg_pool').output) if not os.path.exists(path_to_save_features): os.mkdir(path_to_save_features) for cat in [ 'ADI', 'MUC', 'BACK', 'LYM', 'NORM', 'DEB', 'MUS', 'STR', 'TUM' ]: X = [] for filename in tqdm(os.listdir(os.path.join(path_to_tiles, cat))): try: tile = Image.open(os.path.join(path_to_tiles, cat, filename)) tile = to_pil(cca.stretch(from_pil(tile))) tile = np.array(tile) features = model.predict(preprocess_input(tile[np.newaxis]), batch_size=1) X.append(features) except ZeroDivisionError: pass np.save(os.path.join(path_to_save_features, f'{cat}.npy'), np.array(X))
def equalize_colors_file(input_file, method_name, on_condor=False): equalize_image = methods[method_name] print (input_file) try: image = Image.open(input_file) except: print("Failed to open image %s, skipping." % input_file) new_image = to_pil(equalize_image(from_pil(image))) new_image.save(input_file) if on_condor: f = open(input_file+ ".done", "w") f.writelines("test\n") f.close() # end of "for each image in the folder" return
# -*- coding: utf-8 -*- import sys from PIL import Image from colorcorrect.algorithm import stretch, grey_world, retinex, retinex_with_adjust, max_white from colorcorrect.algorithm import standard_deviation_weighted_grey_world from colorcorrect.algorithm import standard_deviation_and_luminance_weighted_gray_world from colorcorrect.algorithm import automatic_color_equalization from colorcorrect.algorithm import luminance_weighted_gray_world from colorcorrect.util import from_pil, to_pil if __name__ == "__main__": img = Image.open(sys.argv[1]) # img.show() to_pil(stretch(from_pil(img))) to_pil(grey_world(from_pil(img))) to_pil(retinex(from_pil(img))) to_pil(max_white(from_pil(img))) to_pil(retinex_with_adjust(retinex(from_pil(img)))) to_pil(standard_deviation_weighted_grey_world(from_pil(img), 20, 20)) to_pil( standard_deviation_and_luminance_weighted_gray_world( from_pil(img), 20, 20)) to_pil(luminance_weighted_gray_world(from_pil(img), 20, 20)) to_pil(automatic_color_equalization(from_pil(img)))
from PIL import Image import colorcorrect.algorithm as cca from colorcorrect.util import from_pil, to_pil img = Image.open('demo.jpg') # img = to_pil(cca.stretch(cca.gray_world(from_pil(img)))) img = to_pil(cca.automatic_color_equalization(from_pil(img))) img.save("result.jpg", quality=100)
print("Creation of the directory %s failed" % colcor_path) else: print("Successfully created the directory %s " % colcor_path) Iter = 0 print("Executing...") for thisFile in os.listdir(target_dir): file_name = os.path.join(target_dir, thisFile) if os.path.isfile(file_name): file_name = os.path.join(target_dir, thisFile) Iter += 1 print("\r" + str(Iter) + '/' + str(file_count), end='') img = Image.open(file_name) img = to_pil(cca.stretch(cca.gray_world(from_pil(img)))) img = ImageOps.autocontrast(img, 0) img = img.filter(ImageFilter.SHARPEN) basename = os.path.basename(file_name) abs_filename = colcor_path + '/' + basename img.save(abs_filename, quality=95) print("\nDone.")
files_glob.extend( glob.glob( os.path.join(".", "negative", "**", files), recursive=True, )) for i, file in enumerate(files_glob): img = Image.open(file) if args.negative is True: print("Invert colors.") img = ImageOps.invert(img) if args.colorautoadjust is True: print("Using automatic color equalization.") img = to_pil(cca.automatic_color_equalization(from_pil(img))) if args.colorstretch is True: print("Using gray world color equalization.") img = to_pil(cca.stretch(cca.grey_world(from_pil(img)))) if img.mode == "RGBA": img.load() background = Image.new("RGB", img.size, (255, 255, 255)) background.paste(img, mask=img.split()[3]) img = background if args.monochrome is True: if img.mode == "L" or img.mode == "LA": pass
modified = time.ctime(os.path.getmtime('data/bbox.txt')) bbox = open('data/bbox.txt').readlines()[0] cmd = '/opt/local/bin/convert data/temp.jpg -matte -virtual-pixel transparent -distort perspective "' + bbox + '" data/temp.jpg' print center('working...') os.system(cmd) print del_line + center('[done]') + end + '\n' # convert to B&W, adjust levels, etto_pil(cca.retinex(from_pil(img))).show()c print bold + center('Correcting levels') + end + cyan img = Image.open('data/temp.jpg') if convert_bw: img = img.convert('L') if auto_white_balance: img = to_pil(cca.retinex_with_adjust(from_pil(img))) enhancer = ImageEnhance.Contrast(img) img = enhancer.enhance(contrast_adjust) enhancer = ImageEnhance.Brightness(img) img = enhancer.enhance(brightness_adjust) enhancer = ImageEnhance.Sharpness(img) img = enhancer.enhance(sharpness_adjust) print center('contrast: ' + str(contrast_adjust)) print center('brightness: ' + str(brightness_adjust)) print center('sharpness: ' + str(sharpness_adjust)) + end # save temp version to upload to Twitter print '\n' + bold + center('Saving image for Twitter') + end + cyan twitter_image = os.path.join(os.path.sep, __location__, 'data/temp.jpg') img.save(twitter_image)
def extract_tile_features(level, coord, zoom): tile = np.array(zoom.get_tile(level, (coord[1], coord[2]))) tile = Image.fromarray(tile) tile = to_pil(cca.stretch(from_pil(tile))) tile = np.array(tile) return tile
def applyEffectsACE(count, filename, file): # print("{0} > apply ACE em {1}".format(count, pastaSaida + file)) nomeParaSalvar = pastaSaida + file img = Image.open(filename) img = to_pil(cca.automatic_color_equalization(from_pil(img))) img.save(nomeParaSalvar)