def main(): print("1 = Grayscale") print("2 = Negative") print("3 = RGB Mask") print("4 = Sepia") print("5 = Lower Brightness") print("6 = Increase Brightness") print("7 = Blur") print("8 = Emboss\n") choice = int(input("Please choose a filter : ")) c_file = str(input("Please type the path of your file : ")) if (choice == 1): filters.grayscale(get_file_data(c_file)) elif (choice == 2): filters.negative(get_file_data(c_file)) elif (choice == 3): filters.rgb_mask(get_file_data(c_file)) elif (choice == 4): filters.sepia(get_file_data(c_file)) elif (choice == 5): filters.low_bright(get_file_data(c_file)) elif (choice == 6): filters.up_bright(get_file_data(c_file)) elif (choice == 7): filters.blur(get_file_data(c_file)) elif (choice == 8): filters.emboss(get_file_data(c_file)) else: print("Please enter a correct number !") main()
def checkButtons(): global IMAGE_CURRENT, PREV_FILENAME, USER_INPUT, FILENAME, IMAGE_ORIGINAL x = pygame.mouse.get_pos()[0] y = pygame.mouse.get_pos()[1] for button in buttons: if pointInRect(x, y, button.x, button.y, button.w, button.h): if button.title == "Black & White": blackAndWhitePhoto = filters.blackAndWhite( PREV_FILENAME) # call function in filters.py file IMAGE_CURRENT = pygame.image.load(blackAndWhitePhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) PREV_FILENAME = blackAndWhitePhoto elif button.title == "Blur": bluredPhoto = filters.blur(PREV_FILENAME) IMAGE_CURRENT = pygame.image.load(bluredPhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) filters.blurRadius += 1 PREV_FILENAME = bluredPhoto elif button.title == "Invert": invertedPhoto = filters.Invert(PREV_FILENAME) IMAGE_CURRENT = pygame.image.load(invertedPhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) PREV_FILENAME = invertedPhoto elif button.title == "Edge Detection": demonicPhoto = filters.findEdge(PREV_FILENAME) IMAGE_CURRENT = pygame.image.load(demonicPhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) PREV_FILENAME = demonicPhoto elif button.title == "Sharpen": sharpPhoto = filters.sharpen(PREV_FILENAME) IMAGE_CURRENT = pygame.image.load(sharpPhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) filters.sharpness += 2.5 PREV_FILENAME = sharpPhoto elif button.title == "Sepia": sepiaPhoto = filters.diySepia(PREV_FILENAME) IMAGE_CURRENT = pygame.image.load(sepiaPhoto) IMAGE_CURRENT = scaledImage(IMAGE_CURRENT) PREV_FILENAME = sepiaPhoto elif button.title == "Reset": for slider in sliders: slider.Ex = slider.middleX IMAGE_CURRENT = IMAGE_ORIGINAL PREV_FILENAME = FILENAME elif button.title == "New Image": input_check() PREV_FILENAME = FILENAME IMAGE_ORIGINAL = pygame.image.load(FILENAME) IMAGE_ORIGINAL = scaledImage(IMAGE_ORIGINAL) IMAGE_CURRENT = IMAGE_ORIGINAL elif button.title == "Save Final": filters.saveFinal(PREV_FILENAME)
def filter_image(fil, photopath): photo = Image.open('static/' + photopath) if fil == 'Gray': img = filters.gray(photo) elif fil == 'Sepia': img = filters.sepia(photo) elif fil == 'Poster': img = filters.poster(photo) elif fil == 'Blur': img = filters.blur(photo) elif fil == 'Edge': img = filters.edge(photo) elif fil == 'Solar': img = filters.solar(photo) # local save outputpath = mutate_filename(photopath, fil) img.save('static/' + outputpath) return outputpath
def applyFilter(f): global image, workingImage, app if(workingImage == None): app.loadFile() width, height = workingImage["size"][0], workingImage["size"][1] pixels = workingImage["pixels"] if(f == "g"): pixels = filters.grayscale(pixels) elif(f == "t"): minT, maxT = app.minThreshold.get(), app.maxThreshold.get() pixels = filters.grayscale(pixels, lmin=minT, lmax=maxT) elif(f == "b"): pixels = filters.blur(pixels, width, height) elif(f == "n"): pixels = filters.negative(pixels) elif(f == "s"): pixels = filters.sepia(pixels) elif(f == "no"): level, intensity = app.noiseLevel.get(), app.noiseIntensity.get() pixels = filters.noise(pixels, level, intensity) elif(f == "rn"): aggressiveness = app.noiseAggressiveness.get() pixels = filters.removeNoise(pixels, width, height, aggressiveness) elif(f == "d"): pixels = filters.difference(pixels, width, height) elif(f == "c"): pixels = filters.applyMask(pixels, width) elif(f == "bd"): pixels = filters.borderDetection(pixels, width) elif(f == "od"): coordinates = app.mouseCoords color = (0,0,255) pixels, dmp1, dmp2 = filters.objectDetection(pixels, width, height, coordinates, color) else: pass saveImageChanges(pixels) app.updateCanvas() print "Done!" return
def applyFilter(f): global image, lastImage, app if(f == "o"): i = image else: i = "tmp.png" a, width, height, pixels = imageToPixels(lastImage) if(f == "g"): pixels = filters.grayscale(pixels) elif(f == "t"): minT, maxT = app.minThreshold.get(), app.maxThreshold.get() pixels = filters.grayscale(pixels, lmin=minT, lmax=maxT) elif(f == "b"): pixels = filters.blur(pixels, width, height) elif(f == "n"): pixels = filters.negative(pixels) elif(f == "s"): pixels = filters.sepia(pixels) elif(f == "no"): level, intensity = app.noiseLevel.get(), app.noiseIntensity.get() pixels = filters.noise(pixels, level, intensity) elif(f == "rn"): aggressiveness = app.noiseAggressiveness.get() pixels = filters.removeNoise(pixels, width, height, aggressiveness) elif(f == "d"): pixels = filters.difference(pixels, width, height) elif(f == "c"): pixels = filters.applyMask(pixels, width) elif(f == "bd"): pixels = filters.borderDetection(pixels, width) elif(f == "od"): coordinates = app.mouseCoords color = (0,0,255) pixels, dmp1, dmp2 = filters.objectDetection(pixels, width, height, coordinates, color) else: pass saveImage((width, height), pixels, i) lastImage = i app.updateCanvas(i) print "Done!" return
def parse_filters(filters_str): """ Parsing a string to a list-like which contains filter functions to modify digit image. Parameters ---------- filters_str: str A string constaing list of name of filters separated comma. Returns ------- A list-like containing filter functions. """ fltrs = [] for part in str(filters_str).lower().split(","): if part == "blur": fltrs.append(filters.blur(1)) elif part == "distort": fltrs.append(filters.distort(18)) return fltrs
img = Image.open(image_input_path) # 1. 转为灰度图 image_gray_output_path = os.path.join(output_root_path, "test_gray.jpg") img_gray = convert_to_gray_image(img) image_save_to_file(img_gray, image_gray_output_path) # 2. 转为缩略图 image_thumbnail_output_path = os.path.join(output_root_path, "test_thumbnail.jpg") img_thumbnail = image_convert_to_thumbnail(img.copy()) image_save_to_file(img_thumbnail, image_thumbnail_output_path) # 3. 各种filter,如模糊 image_blur_output_path = os.path.join(output_root_path, "test_blur.jpg") img_blur = blur(img) image_save_to_file(img_blur, image_blur_output_path) # 4. crop图像 image_crop_output_path = os.path.join(output_root_path, "test_crop.jpg") roi_box = [0, 0, 300, 200] img_crop = crop_image(img, roi_box) image_save_to_file(img_crop, image_crop_output_path) # 5. resize图像 image_resize_output_path = os.path.join(output_root_path, "test_resize.jpg") w, h = img.size img_crop = resize_image(img, (int(w / 3), int(h / 3))) image_save_to_file(img_crop, image_resize_output_path)
#captures video files or default webcam = 0 source.vin(640,480,'') #leaving the path = '' sets to webcam n, m = 1,10 #n=number of max frames, m= a divsor for output RT,IM,frame,diag = True,True,0,white while RT and (frame < n): #Real-Time Loop=> 'esc' key turns off p.start()#-----------performance:msec-------CPU #compute loop::::::::::::::::::::::::::::::::::::::::::: im = source.read() #get one frame #[1]-----gray scale conversion--------------[1] im = filters.gs(im) imc = filters.color(im) #used for colors #[1]-----thresholding-----------------------[1] im2 = filters.thresh(im,200,255) #[1]-----smoothing--------------------------[1] im2 = filters.blur(im2,5) #[2]-----shape collection-------------------[2] imw = im2.copy() #make a deep copy=>cont is destructive cont = shapes.contours(im2) #im2 destroyed, now use im4 ims = filters.white(filters.color(im)) #white color const #[2]-----contour filtering-------------------[2] cont = shapes.filter_by_area(cont,600) #remove small shapes fast #[3]-----find best shapes--------------------[3] s_f = shapes.match_features(train_c,cont,0.1) #len(s_f) <= 2 #[4]-----kalman-filter-----------------------[4] v = target.follow(s_f,cont) #returns smoothed c1,c2,scale,angle #[4]-----kalman-filter-----------------------[4] px,py = np.int32(v[0]),np.int32(v[1]) qx,qy = np.int32(v[2]),np.int32(v[3]) #these are the smoothed scale,angle values = (v[4],v[5])
grayscale_matrix) image_matrix2 = image_io.read_file("images/shrek2.jpg") reds_matrix = filters.red_stripes(image_matrix2) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek2_image.png", reds_matrix) image_matrix3 = image_io.read_file("images/shrek3.jpg") invert = filters.invert_colors(image_matrix3) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek3_image.png", invert) image_matrix4 = image_io.read_file("images/shrek4.jpg") flip = filters.flip(image_matrix4) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek4_image.png", flip) image_matrix5 = image_io.read_file("images/shrek5.jpg") sepia = filters.sepia(image_matrix5) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek5_image.png", sepia) image_matrix6 = image_io.read_file("images/shrek6.jpg") threshold = filters.threshold(image_matrix6) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek6_image.png", threshold) image_matrix7 = image_io.read_file("images/shrek7.jpg") blur = filters.blur(image_matrix7) image_io.write_to_file( "/home/oluwatosin/csci_100/lab_9/outputs/shrek7_image.png", blur)
def interpret_command(command, nest_level): """ String, String --> None Depending on the current menu, executes a command based on user input as provided in the "command" parameter """ global curr_image if nest_level == "main": #interpret input assuming main menu if command == "F": display_menu("file") elif command == "I": if curr_image is not None: display_menu("filter") else: print("Please load an image first") elif command == "Q": sys.exit() else: print("Invalid command") elif nest_level == "file": #interpret input assuming file menu if command == "L": open_new_image() elif command == "S": save_image_as() elif command == "T": list_open_images() elif command == "P": curr_image = select_image() elif command == "C": close_image() elif command == "H": show(select_image()) elif command == "B": return else: print("Invalid command") elif nest_level == "filter": #interpret input assuming filter menu if command == "C": display_menu("bright") elif command == "A": display_menu("color") elif command == "T": display_menu("trans") elif command == "S": display_menu("blur") elif command == "B": return else: print("Invalid command") elif nest_level == "bright": if command == "M": print("Brightness scale (%)?") while True: #Sanitize the input try: filters.modify_brightness(curr_image, int(input(">: "))) break except ValueError: #input is a non-integer print("Please enter an integer value") elif command == "X": filters.extreme_contrast(curr_image) elif command == "B": return else: print ("Invalid command") elif nest_level == "trans": if command == "H": filters.flip_horizontal(curr_image) elif command == "V": filters.flip_vertical(curr_image) elif command == "B": return else: print ("Invalid command") elif nest_level == "blur": if command == "L": filters.blur(curr_image) elif command == "E": print("Threshold? Recommended values: ~7-18") filters.detect_edges(curr_image, int(input(">: "))) elif command == "B": return else: print ("Invalid command")
def test_get_filters(self): test_cases = [ ((28, 255, 10, (3, 10), 230, True, None), ([ "numpy.lib.function_base.vectorize", "numpy.lib.function_base.vectorize", "function resize_seq.<locals>.resize_image", "function spacing_seq.<locals>.add_spacing", ], [])), ((28, 255, 10, (3, 10), 230, True, [ filters.blur(), filters.distort(20), ]), ([ "numpy.lib.function_base.vectorize", "numpy.lib.function_base.vectorize", "function blur.<locals>.blur_image", "function distort.<locals>.distort_image", "function resize_seq.<locals>.resize_image", "function spacing_seq.<locals>.add_spacing", ], [])), ((28, 255, 10, (3, 10), 230, False, None), ([ "numpy.lib.function_base.vectorize", "numpy.lib.function_base.vectorize", "function resize_seq.<locals>.resize_image", "function spacing_seq.<locals>.add_spacing", ], [ "function resize.<locals>.resize_image", ])), ((28, 255, 10, (3, 10), 230, False, [ filters.blur(), filters.distort(20), ]), ([ "numpy.lib.function_base.vectorize", "numpy.lib.function_base.vectorize", "function resize_seq.<locals>.resize_image", "function spacing_seq.<locals>.add_spacing", ], [ "function blur.<locals>.blur_image", "function distort.<locals>.distort_image", "function resize.<locals>.resize_image", ])), ] for test, expected in test_cases: exist_processing, exist_postprocessing = generator.get_filters( *test) expected_processing, expected_postprocessing = expected self.assertEqual(len(exist_processing), len(expected_processing)) for t, e in zip(exist_processing, expected_processing): self.assertTrue( repr(t).find(e) >= 0, msg="unexpected filter {}, expected is {}".format( repr(t), e)) self.assertEqual(len(exist_postprocessing), len(expected_postprocessing)) for t, e in zip(exist_postprocessing, expected_postprocessing): self.assertTrue( repr(t).find(e) >= 0, msg="unexpected filter {}, expected is {}".format( repr(t), e))
print("W)eighted grayscale X)treme contrast V) Save As") print("Q)uit") command = input("Selection: ") if command in ["B", "E", "P", "S", "T", "W", "X", "Q", "L", "V"]: if command == "L": img = get_image() imaged_loaded = True show(img) elif imaged_loaded == False: print("No image loaded") elif command == "B": img = filters.blur(img) show(img) elif command == "E": threshold = int(input("Threshold: ")) img = filters.detect_edges_better(img, threshold) show(img) elif command == "P": img = filters.posterize(img) show(img) elif command == "S": img = filters.scatter(img) show(img)
def upload(form): message = None # temporary data storage tmp_img_dir = os.path.abspath("") + "/tmp/" history = None h_lines = list() write_history = True # image infos ispublic = None img_type = str() img_width = str() img_height = str() # upload file to tmp if "filename" in form: fileitem = form["filename"] # check if public img if "public" in form: ispublic = True else: ispublic = False # temporary, store file test_img_path = tmp_img_dir + datetime.datetime.now().strftime( "%Y_%m_%d-%H_%M_%S-%f") open(test_img_path, 'wb').write(fileitem.file.read()) try: img = Image.open(test_img_path) img_width, img_height = img.size img_type = img.format.lower() img_type = img_type.replace("jpeg", "jpg") # create extension aware path tmp_img_path = test_img_path + "." + img_type img.save(tmp_img_path) except Exception as err: os.remove(test_img_path) html_body = """<p>Invalid image file (no jpg, png or gif) </p> <p>Returning to index page...</p> """ print(util.html_redirect("index.cgi", 3, html_body)) sys.exit() os.remove(test_img_path) # userID should always be re-transmitted if "userID" in form: user = form.getvalue("userID") # get history data history = os.path.join(os.path.dirname(__file__), tmp_img_dir + user + ".txt") if os.path.isfile(history): hf = open(history, 'r') h_lines = hf.read().splitlines() hf.close() strip = None for cookie in map(strip, h_lines[0].split(',')): (key, value) = cookie.split('=') if key == "public": if value == "True": ispublic = True else: ispublic = False if key == "type": img_type = value if key == "width": img_width = value if key == "height": img_height = value else: # ispublic, orignal image path # store relative path in database h_lines = [ """public={},type={},width={},height={}""".format( ispublic, img_type, img_width, img_height), tmp_img_path ] # apply filter if "filter" in form: fil = form.getvalue("filter") tmp_img_path = tmp_img_dir + datetime.datetime.now().strftime("%Y_%m_%d-%H_%M_%S-%f")\ + "." + img_type if fil == "border": filters.border(h_lines[1], tmp_img_path, "Black", "2x2") elif fil == "lomo": filters.lomo(h_lines[1], tmp_img_path) elif fil == "lens": filters.lens_flare(h_lines[1], tmp_img_path, img_width, img_height) elif fil == "blackwhite": filters.black_white(h_lines[1], tmp_img_path, img_width, img_height) elif fil == "bur": filters.blur(h_lines[1], tmp_img_path) else: # no filter Image.open(h_lines[1]).save(tmp_img_path) h_lines.append(tmp_img_path) if "undo" in form and len(h_lines) > 2: # remove latest latest = h_lines[len(h_lines) - 1] h_lines.remove(latest) try: os.remove(latest) except: pass elif "discard" in form: # delete temporary files try: for i, hl in enumerate(h_lines, 0): if i != 0: os.remove(hl) # remove images except: pass os.remove(history) # extit to index page print(util.html_redirect("index.cgi")) sys.exit() elif "finish" in form: img_dir = "/img/" latest = h_lines[len(h_lines) - 1] img_path = latest.replace(tmp_img_dir, img_dir) img_path = img_path.replace(os.path.abspath(""), "") os.rename(latest, img_path.replace("/img/", "img/")) it = ImageTable() if it.insert((user, img_path), ispublic): pass try: h_lines.remove(latest) for i, hl in enumerate(h_lines, 0): if i != 0: os.remove(hl) # remove image except: pass os.remove(history) # remove history # exit to index page print(util.html_redirect("index.cgi")) sys.exit() else: pass if write_history: # write history hf = open(history, 'w') for l in h_lines: hf.write(l + "\r\n") hf.close() # if False: # try: # public = form.getvalue("public") # fstorage_name = str(datetime.datetime.now()) # fstorage_name = fstorage_name.replace(":", "-") # fstorage_name = fstorage_name.replace(" ", "_") # fstorage_name = fstorage_name.replace(".", "-") # root_path = img_path + fstorage_name # fn = os.path.basename(fileitem.filename) # if not fn.lower().endswith(('.png', '.jpg', '.jpeg', '.gif')): # message = 'Failed to upload file: ' + fn + '\r\nInvalid ending' # else: # open(os.path.abspath("") + root_path, # 'wb').write(fileitem.file.read()) # it = ImageTable() # if it.insert((user, root_path), public): # message = 'The file "' + fn + '" was uploaded successfully' # else: # message = 'Failed to upload file: ' + fn # except Exception as err: # message = 'Failed to upload file' # pass if len(h_lines) < 3: undo_disable_str = "disabled" else: undo_disable_str = "" host = "" if os.environ.has_key("ASSIGNMENT1_SERVICE_HOST"): host = "http://root-csci4140-projects.a3c1.starter-us-west-1.openshiftapps.com" path = h_lines[len(h_lines) - 1].replace(os.path.abspath(""), "") print("""\ Content-Type: text/html\n <html> <body> <img src="{}{}" alt="HTML5 Icon" style="height: 100%; width: 100%; max-width: 400px; max-height: 400px"> <form enctype="multipart/form-data" action="index.cgi" method="post"> <p>Filter: <input type="hidden" name="userID" value="{}"></input> <input type="hidden" name="action" value="upload"></input> <select onchange="this.form.submit()" name="filter"> <option value="f_init">Choose</option> <option value="no_filter">None</option> <option value="border">Border</option> <option value="lomo">Lomo</option> <option value="lens">Lens Flare</option> <option value="blackwhite">Black White</option> <option value="bur">Bur</option> </select> </form> <form action="index.cgi" method="post"> <input type="hidden" name="action" value="upload"></input> <p> <button type="submit" name="discard" value="df">Discard</button> <button type="submit" name="undo" value="dd" {}>Undo</button> <button type="submit" name="finish" value="xc">Finish</button> </p> <input type="hidden" name="userID" value="{}"></input> </form> </body> </html> """.format(host, path, user, undo_disable_str, user))