def image_with_contours_gen(image, bm1, bm2, color1, color2, bottom, up, left, right, width, height, box_color, perf_box, perf_col): # INPUTS: image of size (192,192,160), bm1 is the first set of contours (192,192,160,n_contours), bm2 is the second set of contours, col1 is the first set of colors, col2 is the second set of colors output = image output = gray2rgb(output) n_contours = bm1.shape[2] for contour_num in range(n_contours): edges = imfilter(bm1[:, :, contour_num] * 255, 'find_edges') output[edges > 0] = np.array(color1[contour_num, :]) for contour_num in range(n_contours): edges = imfilter(bm2[:, :, contour_num] * 255, 'find_edges') output[edges > 0] = np.array(color2[contour_num, :]) output[up, left:(left + width)] = box_color output[bottom, left:(left + width)] = box_color output[up:(up + height), left] = box_color output[up:(up + height), right] = box_color [left, right, up, bottom] = perf_box width = right - left height = bottom - up output[up, left:(left + width)] = perf_col output[bottom, left:(left + width)] = perf_col output[up:(up + height), left] = perf_col output[up:(up + height), right] = perf_col return output
def check_invert_contrast(im): hist = np.histogram(im)[0] score = np.sum(hist[-3:]) total = np.sum(hist) if score / float(total) > 0.15: return imfilter((1 - im), 'edge_enhance') else: return imfilter(im, 'edge_enhance')
def image_with_contours_new(image, bm1, bm2, color1=rgb_dark, color2=rgb_light): output = image output = gray2rgb(output) n_contours = bm1.shape[2] for contour_num in range(n_contours): edges = imfilter(bm1[:,:,contour_num]*255, 'find_edges') output[edges>0] = np.array(color1[contour_num,:]) for contour_num in range(n_contours): edges = imfilter(bm2[:,:,contour_num]*255, 'find_edges') output[edges>0] = np.array(color2[contour_num,:]) return output
def image_with_2contours(image, mask1, mask2, color1=rgb_dark, color2=rgb_light): vmin = -1000 vmax = 3000 output = ((image - vmin) * 255 / (vmax - vmin)).astype(np.uint8) mask1 = imfilter(mask1*255, 'find_edges') #mask1 = mask1.filter(ImageFilter.FIND_EDGES) mask2 = imfilter(mask2*255, 'find_edges') output = gray2rgb(output) output[mask1 > 0] = np.array(color1) output[mask2 > 0] = np.array(color2) return output
def image_with_4contours(image, true1, true2, pred1, pred2, color1, color2): output = image true1 = imfilter(true1*255, 'find_edges') true2 = imfilter(true2*255, 'find_edges') pred1 = imfilter(pred1*255, 'find_edges') pred2 = imfilter(pred2*255, 'find_edges') output = gray2rgb(output) output[true1 > 0] = np.array(color1) output[true2 > 0] = np.array(color1) output[pred1 > 0] = np.array(color2) output[pred2 > 0] = np.array(color2) return output
def image_with_contours_gen(image, bm1, bm2, color1, color2): # INPUTS: image of size (192,192,160), bm1 is the first set of contours (192,192,160,n_contours), bm2 is the second set of contours, col1 is the first set of colors, col2 is the second set of colors output = image output = gray2rgb(output) n_contours = bm1.shape[2] for contour_num in range(n_contours): edges = imfilter(bm1[:, :, contour_num] * 255, 'find_edges') output[edges > 0] = np.array(color1[contour_num, :]) for contour_num in range(n_contours): edges = imfilter(bm2[:, :, contour_num] * 255, 'find_edges') output[edges > 0] = np.array(color2[contour_num, :]) return output
def sharpen_(cached,size): out=cached for k in range(size): out=misc.imfilter(out,'sharpen') print '.', print '->sharpen' return out;
def blur_(cached, size): out = cached for k in range(size): out = misc.imfilter(out, "blur") print ".", print "->Blur", size return out
def generate_extra_data(n=3000, file_name=None, load_file=None, seed=None, rotate=True, emboss=True, elastic=False): print "Creating {} new images".format(n) if load_file: if not load_file.startswith("data/"): load_file = "data/" + load_file return np.load(load_file +".npy"), np.load(load_file+"_targets.npy") if seed: np.random.seed(seed) X = np.load("data/mnist_train_extra_inputs.npy") Y = np.load("data/mnist_train_extra_outputs.npy") positions = np.random.random_integers(0, X.shape[0]-1, n) transformed = X[positions,:] targets = Y[positions] final = np.zeros((n,48*48)) angles = np.random.uniform(0,359, n) for i in range(n): temp = transformed[i,:].reshape((28,28)) temp = imresize(temp, (48,48)) if rotate: temp = imrotate(temp, angles[i], reshape=False) if emboss: temp = imfilter(temp,"emboss") if elastic: temp = elastic_distortion(temp, size=48) final[i,:] = temp.flatten() if file_name: if not file_name.startswith("data/"): file_name = "data/" + file_name np.save(file_name, final) np.save(file_name + "_targets", targets) return final, targets
def sharpen_(cached, size): out = cached for k in range(size): out = misc.imfilter(out, "sharpen") print ".", print "->Sharpen", size return out
def blur_(cached,size): out=cached for k in range(size): out=misc.imfilter(out,'blur') print '.', print '->blur' return out;
def load_train_data(im_dir, dim=(4, 4)): # Load Images print("-- Reading Images") training_paths = pathlib.Path(im_dir).glob('*/images/*.png') training_sorted = sorted([x for x in training_paths]) train_ims = np.array([ rgb2gray(imageio.imread(str(x)))[:256, :256] for x in training_sorted ]) train_ims = np.array([ check_invert_contrast(train_ims[x]) for x in range(train_ims.shape[0]) ]) #Augment Code Added 1/16 train_ims_blurred = np.array( [imfilter(train_ims[x], 'blur') for x in range(train_ims.shape[0])]) train_ims = np.concatenate((train_ims, train_ims_blurred), axis=0) downsample = np.concatenate( [split_data(train_ims[x], dim=dim) for x in range(train_ims.shape[0])], axis=0) downsample_ims = downsample.reshape( (downsample.shape[0], downsample.shape[1], downsample.shape[2], 1)) print downsample_ims.shape # Load Labels print("-- Reading Labels") label_paths = pathlib.Path(im_dir).glob('*/masks/') label_sorted = sorted([x for x in label_paths]) labels = np.array([ np.sum([ rgb2gray(imageio.imread(str(x))) for x in pathlib.Path(y).glob('*.png') ], axis=0)[:256, :256] for y in label_sorted ]) #For Augment Added 1/16 labels2 = np.copy(labels) labels = np.concatenate((labels, labels2), axis=0) downsample_l = np.concatenate( [split_data(labels[x], dim=dim) for x in range(labels.shape[0])], axis=0) downsample_labs = downsample_l.reshape( (downsample_l.shape[0], downsample_l.shape[1], downsample_l.shape[2], 1)) print downsample_labs.shape # Add Zero Arrays add_zero_ims = np.zeros((int(0.15 * downsample.shape[0]), downsample.shape[1], downsample.shape[2], 1)) add_zero_labs = np.zeros((int(0.15 * downsample.shape[0]), downsample.shape[1], downsample.shape[2], 1)) final_ims = np.concatenate((downsample_ims, add_zero_ims), axis=0).astype('float32') final_labs = np.concatenate((downsample_labs, add_zero_labs), axis=0).astype('float32') cand = list(np.linspace(0, final_ims.shape[0] - 1, final_ims.shape[0])) idx = shuffle([int(x) for x in cand]) shuffle_ims = final_ims[idx, :, :, :] shuffle_labs = final_labs[idx, :, :, :] return shuffle_ims.reshape(final_ims.shape), shuffle_labs.reshape( final_labs.shape)
def get_chest_boundary(im, plot=False): size = im.shape[1] if plot == True: f, plots = plt.subplots(6, 1, figsize=(5, 30)) binary = im < -320 if plot == True: plots[0].axis('off') plots[0].imshow(binary, cmap=plt.cm.bone) cleared = clear_border(binary) temp_label = label(cleared) for region in regionprops(temp_label): if region.area < 300: for coordinates in region.coords: temp_label[coordinates[0], coordinates[1]] = 0 cleared = temp_label > 0 label_img = label(cleared) for region in regionprops(label_img): if region.eccentricity > 0.99 \ or region.centroid[0] > 0.90 * size \ or region.centroid[0] < 0.12 * size \ or region.centroid[1] > 0.88 * size \ or region.centroid[1] < 0.10 * size \ or (region.centroid[1] > 0.46 * size and region.centroid[1] < 0.54 * size and region.centroid[ 0] > 0.75 * size) \ or (region.centroid[0] < 0.2 * size and region.centroid[1] < 0.2 * size) \ or (region.centroid[0] < 0.2 * size and region.centroid[1] > 0.8 * size) \ or (region.centroid[0] > 0.8 * size and region.centroid[1] < 0.2 * size) \ or (region.centroid[0] > 0.8 * size and region.centroid[1] > 0.8 * size): for coordinates in region.coords: label_img[coordinates[0], coordinates[1]] = 0 if plot == True: plots[1].axis('off') plots[1].imshow(label_img, cmap=plt.cm.bone) region_n = np.max(label_img) selem = disk(10) filled = np.zeros(cleared.shape, np.uint8) for i in range(1, region_n + 1): curr_region = np.zeros(cleared.shape, np.uint8) curr_region[label_img == i] = 1 curr_region = binary_closing(curr_region, selem) curr_region = binary_fill_holes(curr_region) filled[curr_region == 1] = 1 if plot == True: plots[2].axis('off') plots[2].imshow(filled, cmap=plt.cm.bone) filled_edge = misc.imfilter(filled.astype(np.float64), 'find_edges') / 255 if plot == True: plots[3].axis('off') plots[3].imshow(filled_edge, cmap=plt.cm.bone) return filled_edge
def __smooth_group(self, arr): for i in range(0, self.smoothing): arr = misc.imfilter(arr, 'smooth'); #arr = ndimage.filters.gaussian_filter(deepcopy(arr), 5, cval=255); for y in range(0, arr.shape[0]): for x in range(0, arr.shape[1]): arr[y][x] = 255 if arr[y][x] > self.threshold else 0; return arr;
def __smooth_group(self, arr): for i in range(0, self.smoothing): arr = misc.imfilter(arr, 'smooth') #arr = ndimage.filters.gaussian_filter(deepcopy(arr), 5, cval=255); for y in range(0, arr.shape[0]): for x in range(0, arr.shape[1]): arr[y][x] = 255 if arr[y][x] > self.threshold else 0 return arr
def load_filtered_mnist_images(): """ :param *args: an option list :return: np.array of mnist images and np.array of mnist image classes The images are returned filtered by several image filters. Any filters that can be used with scipy.misc.imfilter may be used. """ filters = ['emboss', 'blur'] imgs, clss = load_raw_mnist_images() for index, img in enumerate(imgs): for filter in filters: img = imfilter(img, filter) imgs[index, :, :] = img return imgs, clss
def mask_pos(cutnodule, max_layer): results = [] #label the nodule first nodule = cutnodule[max_layer] [min_row, min_col, max_row, max_col] = regionprops(label(nodule))[0].bbox filled_edge = imfilter(nodule.astype(np.float64), 'find_edges') / 255 for row in range(0, filled_edge.shape[0]): for col in range(0, filled_edge.shape[1]): if filled_edge[row, col] == 1: results.append([row, col]) boundingbox = [[min_row, min_col], [min_row, max_col], [max_row, max_col], [max_row, min_col]] return results, boundingbox
def load_filtered_mnist_images(): """ :param *args: an option list :return: np.array of mnist images and np.array of mnist image classes The images are returned filtered by several image filters. Any filters that can be used with scipy.misc.imfilter may be used. """ filters = ['emboss', 'blur'] imgs, clss = load_raw_mnist_images() for index, img in enumerate(imgs): for filter in filters: img = imfilter(img, filter) imgs[index,:,:] = img return imgs, clss
def blur_or_sharpen(im, prob_blur=0.25, min_sigma=0.5, max_sigma=3.0, prob_sharpen=0.25, prng=np.random): prob_total = prob_blur + prob_sharpen assert prob_total <= 1.0 uniform = prng.uniform() if uniform <= prob_blur: return blur(im, min_sigma=min_sigma, max_sigma=max_sigma, prng=prng) elif uniform <= prob_total: return np.expand_dims(imfilter(np.squeeze(im), "sharpen"), axis=-1) else: return im
def run_tests(w, payload, k_range): os.chdir(os.path.dirname(os.path.abspath(__file__))) ROOT = os.getcwd() if not os.path.isdir("results"): os.mkdir("results") for k in k_range: for fn in os.listdir(os.path.join(ROOT, "pics")): src = misc.imread(os.path.join(ROOT, "pics", fn)) dst = os.path.join(ROOT, "results", "%s-%d" % (fn.split(".")[0], k)) try: os.mkdir(dst) except EnvironmentError: print "skipping", fn, k continue os.chdir(dst) out = w.embed(src, payload, k) misc.imsave("orig.png", out) print "%s (k = %d)" % (fn, k) print "=" * 20 print "Minimum JPG quality:", test_jpg(w, out) print "Max Gaussian sigma:", test_filter( w, out, "gauss-%s.png", gaussian_filter, [i / 10.0 for i in range(1, 50)]) print "Max Laplacian of Gaussian sigma:", test_filter( w, out, "log-%s.png", gaussian_laplace, [i / 10.0 for i in range(1, 50)]) print "Max tv-denoising weight:", test_filter( w, out, "tv-%s.png", tv_denoise, range(50, 1000, 25)) print "Max noise ratio: ", test_filter( w, out, "noise-%s.png", add_noise, [i / 20.0 for i in range(1, 20)]) print "Max random block coverage: ", test_filter( w, out, "blocks-%s.png", lambda img, k: add_blocks(img, k, 50, 50), [i / 20.0 for i in range(1, 20)]) for flt in [ "contour", "detail", "edge_enhance", "edge_enhance_more", "emboss", "find_edges", "smooth", "smooth_more", "sharpen" ]: print "Max iterations of %r:" % (flt, ), test_recursive_filter( w, out, "%s-%%s.png" % (flt, ), lambda img: misc.imfilter(img, flt), range(1, 30)) print
def ordered_combinatorial4(im): """ Encode the image using combinatorial dithering for halftone with 2^4 levels Parameters ---------- im: input image Return ------- binary: output image """ masked = (16.0 / 255.0) * _spm.imfilter(im, 'edge_enhance') masked = _np.floor(masked).astype('uint8') masked[masked > 15] = 15 binary = _compiled.halftone.ordered_comb4_iterator(masked) return binary
def wfm(FG, GT): dGT = np.asarray(GT, np.float32) dGT /= (GT.max() + 1e-8) E = np.abs(FG - dGT) Dst, Idxt = distance(dGT, return_indices=True) Et = E Et[~GT] = Et[Idxt[~GT]] EA = imfilter(Et, 'blur') MIN_E_EA = E MIN_E_EA[GT & EA < E] = EA[GT & EA < E] B = np.ones(GT.shape) B[~GT] = 2.0 - 1 * math.exp(math.log(1 - 0.5) / 5. * Dst[~GT]) Ew = np.multiply(MIN_E_EA, B) TPw = np.sum(dGT[:] - np.sum(np.sum(Ew[GT]))) FPw = np.sum(np.sum(Ew[~GT])) R = np.mean(Ew[GT]) P = TPw
def mask2contours(mask): sh = mask.shape contours = np.zeros((sh[0],sh[1],sh[2])) n_slices = sh[2] for s in range(n_slices): if s>0 and np.sum(mask[:,:,s-1].flatten())==0: contours[:,:,s] = mask[:,:,s] elif s<(n_slices-1) and np.sum(mask[:,:,s+1].flatten())==0: contours[:,:,s] = mask[:,:,s] else: diff = np.abs(mask[:,:,s]*1 - mask[:,:,s-1]*1)>0 imf = imfilter(mask[:,:,s].astype('int'), 'find_edges') if np.sum(diff.flatten()>0): contours[:,:,s] = (diff+imf)>0 else: contours[:, :, s] = imf return contours
def __generalized_bayer(image, masks): """ Convert a grayscale image in binary halftone image with n levels. Parameters ---------- * im: numpy matrix, original grayscale image * masks: numpy array, set with all dot patterns used in halftone Return ---------- * binary: numpy matrix, dithered binary image Written by Pedro Garcia Freitas <*****@*****.**> Copyright 2011 by Pedro Garcia Freitas see: http://www.sawp.com.br """ # create and rescale new image to fit levels (levels, m, n) = masks.shape (h, l) = image.shape (step_x, step_y) = masks[0].shape masked = (levels / 255.0) * _spm.imfilter(image, 'edge_enhance') masked = _np.floor(masked).astype('uint8') masked[masked >= levels] = levels - 1 binary = _np.zeros((m * h, n * l)) # generate the halftoned image_path k = 0 r = 0 for i in range(h): for j in range(l): mask = int(masked[i, j]) selected = masks[mask] xs = i + k xf = i + k + step_x ys = j + r yf = j + r + step_y binary[xs:xf, ys:yf] = selected[:, :] r = r + step_x - 1 r = 0 k = k + step_y - 1 return binary
def read_image(filename, show=True, thresh = 120): #import pdb;pdb.set_trace() img = spm.imread(filename, flatten = True) #img = spm.lena() img = spm.imresize(img, (100,100)) img = spm.imfilter(img, ftype='find_edges') img = (img > thresh) img = img+0 #remove outer edge img[:,0] = 0 img[:,99] = 0 img[0,:] =0 img[99,:] = 0 if np.sum(img) > (100*100)/2: img = 1-img if show: plt.imshow(img, interpolation='nearest', cmap='Greys') plt.show() return img
def run_tests(w, payload, k_range): os.chdir(os.path.dirname(os.path.abspath(__file__))) ROOT = os.getcwd() if not os.path.isdir("results"): os.mkdir("results") for k in k_range: for fn in os.listdir(os.path.join(ROOT, "pics")): src = misc.imread(os.path.join(ROOT, "pics", fn)) dst = os.path.join(ROOT, "results", "%s-%d" % (fn.split(".")[0], k)) try: os.mkdir(dst) except EnvironmentError: print "skipping", fn, k continue os.chdir(dst) out = w.embed(src, payload, k) misc.imsave("orig.png", out) print "%s (k = %d)" % (fn, k) print "=" * 20 print "Minimum JPG quality:", test_jpg(w, out) print "Max Gaussian sigma:", test_filter(w, out, "gauss-%s.png", gaussian_filter, [i/10.0 for i in range(1,50)]) print "Max Laplacian of Gaussian sigma:", test_filter(w, out, "log-%s.png", gaussian_laplace, [i/10.0 for i in range(1,50)]) print "Max tv-denoising weight:", test_filter(w, out, "tv-%s.png", tv_denoise, range(50,1000,25)) print "Max noise ratio: ", test_filter(w, out, "noise-%s.png", add_noise, [i/20.0 for i in range(1, 20)]) print "Max random block coverage: ", test_filter(w, out, "blocks-%s.png", lambda img, k: add_blocks(img, k, 50, 50), [i/20.0 for i in range(1, 20)]) for flt in ["contour", "detail", "edge_enhance", "edge_enhance_more", "emboss", "find_edges", "smooth", "smooth_more", "sharpen"]: print "Max iterations of %r:" % (flt,), test_recursive_filter(w, out, "%s-%%s.png" % (flt,), lambda img: misc.imfilter(img, flt), range(1, 30)) print
import cv2 import time import pylab as pl from scipy.misc import imresize, imfilter import turtle counter = 1 img = pl.flipud(pl.imread("inputImages/%05d.jpg" % counter)) levels = 8 size = 2**levels img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) turtle.setup(img.shape[1], img.shape[0]) img = imfilter(imresize(img, (size, size)), 'blur') turtle.setworldcoordinates(0, 0, size, -size) turtle.tracer(1000, 0) time.sleep(.5) # hilbert curve turtle code stolen from # falko's python example on stackoverflow # https://codegolf.stackexchange.com/questions/36374/redraw-an-image-with-just-one-closed-curve # define recursive hilbert curve def hilbert(level, angle=90): global img if level == 0:
def image_mani(image_array, mani): return imfilter(image_array, mani)
def random_blur_image(image): return cv2.blur(image, (5, 5)) img = Image.fromarray(image) img = img.filter(ImageFilter.BLUR) return np.array(img) return misc.imfilter(image, 'blur')
def upscale(self, img_path, scale_factor=2, save_intermediate=False, return_image=False, suffix="scaled", patch_size=8, mode="patch", verbose=True, evaluate=True): """ Standard method to upscale an image. :param img_path: path to the image :param scale_factor: scale factor can be any value, usually is an integer :param save_intermediate: saves the intermediate upscaled image (bilinear upscale) :param return_image: returns a image of shape (height, width, channels). :param suffix: suffix of upscaled image :param patch_size: size of each patch grid :param patch_stride: patch stride is generally 1. :param verbose: whether to print messages :param evaluate: evaluate the upscaled image on the original image. """ import os from scipy.misc import imread, imresize, imsave, imfilter # Destination path path = os.path.splitext(img_path) filename = path[0] + "_" + suffix + "(%dx)" % (scale_factor) + path[1] # Read image scale_factor = int(scale_factor) true_img = imread(img_path, mode='RGB') init_height, init_width = true_img.shape[0], true_img.shape[1] if verbose: print("Old Size : ", true_img.shape) if verbose: print("New Size : (%d, %d, 3)" % (init_height * scale_factor, init_width * scale_factor)) images = None img_height, img_width = 0, 0 denoise_models = ['Deep Denoise SR'] if mode == 'patch': # Create patches if self.model_name in denoise_models: if patch_size % 4 != 0: print( "Deep Denoise requires patch size which is multiple of 4.\nSetting patch_size = 8." ) patch_size = 8 images = img_utils.make_patches(true_img, scale_factor, patch_size, verbose) nb_images = images.shape[0] img_height, img_width = images.shape[1], images.shape[2] print("Number of patches = %d, Patch Shape = (%d, %d)" % (nb_images, img_height, img_width)) else: # Use full image for super resolution img_height, img_width = self.__match_denoise_size( denoise_models, img_height, img_width, init_height, init_width, scale_factor) images = imresize(true_img, (img_height, img_width)) images = np.expand_dims(images, axis=0) print("Image is reshaped to : (%d, %d, %d)" % (images.shape[1], images.shape[2], images.shape[3])) # Save intermediate bilinear scaled image is needed for comparison. intermediate_img = None if save_intermediate: if verbose: print("Saving intermediate image.") fn = path[0] + "_intermediate_" + path[1] intermediate_img = imresize( true_img, (init_height * scale_factor, init_width * scale_factor)) imsave(fn, intermediate_img) # Transpose and Process images img_conv = images.transpose((0, 3, 1, 2)).astype('float64') / 255 model = self.create_model(img_height, img_width, load_weights=True) if verbose: print("Model loaded.") # Create prediction for image patches result = model.predict(img_conv, batch_size=128, verbose=verbose) if verbose: print("De-processing images.") # Deprocess patches result = result.transpose((0, 2, 3, 1)).astype('float64') * 255 # Output shape is (original_height * scale, original_width * scale, nb_channels) if mode == 'patch': out_shape = (init_height * scale_factor, init_width * scale_factor, 3) result = img_utils.combine_patches(result, out_shape, scale_factor) else: result = result[ 0, :, :, :] # Access the 3 Dimensional image vector result = np.clip(result, 0, 255).astype('uint8') result = imfilter(result, 'smooth_more') if verbose: print("\nCompleted De-processing image.") if return_image: # Return the image without saving. Useful for testing images. return result if verbose: print("Saving image.") imsave(filename, result) if evaluate: if verbose: print("Evaluating results.") # Convert initial image into correct format if intermediate_img is None: intermediate_img = imresize( true_img, (init_height * scale_factor, init_width * scale_factor)) if mode == 'patch': intermediate_img = img_utils.make_patches(intermediate_img, scale_factor, patch_size, upscale=False) else: img_height, img_width = self.__match_denoise_size( denoise_models, img_height, img_width, init_height, init_width, scale_factor) intermediate_img = imresize(true_img, (img_height, img_width)) intermediate_img = np.expand_dims(intermediate_img, axis=0) intermediate_img = intermediate_img.transpose( (0, 3, 1, 2)).astype('float64') / 255 eval_model = self.create_model(img_height, img_width, load_weights=True) # Evaluating the initial image patches, which gets transformed to the output image, to the input image error = eval_model.evaluate(img_conv, intermediate_img, batch_size=128) print("\nMean Squared Error of %s : " % (self.model_name), error[0]) print("Peak Signal to Noise Ratio of %s : " % (self.model_name), error[1])
# 3.2.2 使用misc.imrotate进行图片的旋转 cat_data2 = misc.imrotate(cat_data, angle=90) # 旋转90度 misc.imsave('cat2.jpg', cat_data2) # 图片保存! plt.imshow(cat_data2) # misc.imshow(cat_angle) # 另一种显示图片的方式---弹框式! # 3.2.3 使用misc.imresize对图片进行缩放 cat_data3 = misc.imresize(cat_data, 0.5) # 缩放为原来的0.5倍 plt.imshow(cat_data3) cat_data3 = misc.imresize(cat_data, (100, 200)) plt.imshow(cat_data3) # 缩放为指定的大小 这里表示100*200*3的jpg格式文件 misc.imsave('cat3.jpg', cat_data3) # 图片保存! # 3.2.4 使用misc.imfilter对图片进行过滤 cat_data4 = misc.imfilter(cat_data, ftype='edge_enhance') # ftype='edge_enhance'填写过滤方式 plt.imshow(cat_data4) cat_data4 = misc.imfilter(cat_data, ftype='blur') # 另一种过滤方式 plt.imshow(cat_data4) cat_data4 = misc.imfilter(cat_data, ftype='detail') # 另一种过滤方式,当然还有其他多种过滤方式,自己查看帮助ctrl+i plt.imshow(cat_data4) '''3.3 图片处理---scipy.ndimage 用于操纵图片,包括:图片移动、图片旋转、图片缩放、图片切割、图片模糊处理...''' import scipy.ndimage as ndimage plt.imshow(misc.face()) # misc.face()是misc的内置图片,该图片是一只熊 face = misc.face(gray=True) # 灰白处理 plt.imshow(face) plt.imshow(face, cmap='gray') face = misc.face(gray=False)
from scipy import misc misc.imshow(misc.imfilter(misc.face(), 'edge_enhance_more'))
def sharpen_(cached,size): for k in range(size): cached=misc.imfilter(cached,'sharpen') print '.', print '->Sharpen',size return cached;
def warpImage(inputIm, image, refIm, H): homography = H inverted_H = np.linalg.inv(homography) input_maxRow = inputIm.shape[0] input_maxCol = inputIm.shape[1] BACKGROUND_PIXEL = inputIm[0][0] print('background_pixel = ', BACKGROUND_PIXEL) ## WARP ## input_TOP_L = np.asarray(homography.dot(np.asarray([0, 0, 1]))) input_TOP_L_actual = input_TOP_L[0][0] / input_TOP_L[0][2], input_TOP_L[0][ 1] / input_TOP_L[0][2] input_TOP_R = np.asarray(homography.dot(np.asarray([input_maxCol, 0, 1]))) input_TOP_R_actual = input_TOP_R[0][0] / input_TOP_R[0][2], input_TOP_R[0][ 1] / input_TOP_R[0][2] input_BOT_L = np.asarray(homography.dot(np.asarray([0, input_maxRow, 1]))) input_BOT_L_actual = input_BOT_L[0][0] / input_BOT_L[0][2], input_BOT_L[0][ 1] / input_BOT_L[0][2] input_BOT_R = np.asarray( homography.dot(np.asarray([input_maxCol, input_maxRow, 1]))) input_BOT_R_actual = input_BOT_R[0][0] / input_BOT_R[0][2], input_BOT_R[0][ 1] / input_BOT_R[0][2] input_coords = [] input_coords.append(input_TOP_L_actual) input_coords.append(input_TOP_R_actual) input_coords.append(input_BOT_L_actual) input_coords.append(input_BOT_R_actual) input_smallest_x = min([x[0] for x in input_coords]) input_greatest_x = max([x[0] for x in input_coords]) input_smallest_y = min([x[1] for x in input_coords]) input_greatest_y = max([x[1] for x in input_coords]) # find 4 corners in new image x_shape = int(input_greatest_x - input_smallest_x) y_shape = int(input_greatest_y - input_smallest_y) newImg = np.zeros((y_shape, x_shape, 3), dtype=np.uint8) for rows in range(newImg.shape[0]): for cols in range(newImg.shape[1]): homogenous_coords = np.asarray( [cols + input_smallest_x, rows + input_smallest_y, 1]) input_coords = np.asarray(inverted_H.dot(homogenous_coords)) # Convert out of homogenous input_coords_normed = (input_coords[0][0] / input_coords[0][2], input_coords[0][1] / input_coords[0][2]) input_coords_actual = (int(input_coords_normed[0]), int(input_coords_normed[1])) if input_coords_actual[0] >= 0 and input_coords_actual[ 0] < inputIm.shape[1]: if input_coords_actual[1] >= 0 and input_coords_actual[ 1] < inputIm.shape[0]: if not np.array_equal( BACKGROUND_PIXEL, inputIm[input_coords_actual[1]][ input_coords_actual[0]]): newImg[rows][cols] = inputIm[input_coords_actual[1]][ input_coords_actual[0]] ## MERGE ## # find 4 corners in new image x_min = min(input_smallest_x, 0) x_max = max(input_greatest_x, refIm.shape[1]) y_min = min(input_smallest_y, 0) y_max = max(input_greatest_y, refIm.shape[0]) x_shape = int(x_max - x_min) y_shape = int(y_max - y_min) stitchedImg = np.zeros((y_shape, x_shape, 3), dtype=np.uint8) for rows in range(stitchedImg.shape[0]): for cols in range(stitchedImg.shape[1]): homogenous_coords = np.asarray( [int(cols + x_min), int(rows + y_min), 1]) input_coords = np.asarray(inverted_H.dot(homogenous_coords)) # Convert out of homogenous input_coords_normed = (input_coords[0][0] / input_coords[0][2], input_coords[0][1] / input_coords[0][2]) input_coords_actual = (int(input_coords_normed[0]), int(input_coords_normed[1])) if rows + (y_min) >= 0 and rows + y_min < refIm.shape[ 0] and cols + x_min < refIm.shape[1] and (cols + (x_min)) >= 0: stitchedImg[rows][cols] = refIm[int(rows + y_min)][int(cols + x_min)] if input_coords_actual[0] >= 0 and input_coords_actual[ 0] < inputIm.shape[1]: if input_coords_actual[1] >= 0 and input_coords_actual[ 1] < inputIm.shape[0]: if not np.array_equal( BACKGROUND_PIXEL, inputIm[input_coords_actual[1]][ input_coords_actual[0]]): stitchedImg[rows][cols] = image[ input_coords_actual[1]][input_coords_actual[0]] fig, ax = plt.subplots(1, 2) img_vec2 = stitchedImg ax[0].imshow(img_vec2) blurred = cv2.medianBlur(stitchedImg, 15) sharpened = misc.imfilter(blurred, 'sharpen') ax[1].imshow(sharpened) plt.title('Merged Shirt with blurring') plt.show()
def Run(self, a, pixelStep, plot_all_figures_): crop_ = 0 #Testing parameter for cutting images vectorComputations = vut.Vector() # Adds up to [input] zeros before integer pad_string = lambda integer : '0'*(nbrOfIndexSpaces-len(str(integer))) + str(integer) # OBS! Can only handle up to 1000 vectors with this setup maxNbrOfVectors = 1000 nbrOfIndexSpaces = len(str(maxNbrOfVectors-1)) maxNbrOfVectors = 10**nbrOfIndexSpaces print 'There is space for: ', maxNbrOfVectors, ' in this calculation' # a is numpy array in two dimensions edges = imfilter(a,'find_edges') edges = where(edges >=1, 1, 0) #Tracing--------------------------------- d = nonzero(edges) #create tuple y = d[0,:], x = d[1,:] vec = [d[0][0],d[1][0]] #Pick first non-zero value as y,x traced_edge = zeros_like(edges) # Matrix to store values in image format # traced_edge[vec[0], vec[1]] = 1 cropping = array([[100,200], [200,300]]) edges2 = edges[cropping[0,0]:cropping[0,1], cropping[1,0]:cropping[1,1]] edges[vec[0], vec[1]] = -2 #Mark starting pixel continue_ = 1 loop_ = 0 size_ = 0 previous_size_ = 0 vec_outline = vut.Vector() vec_outline.AddDimension('x') vec_outline.AddDimension('y') vec_outline.SetName('out_' + pad_string(1)) while continue_: #print 'this: ', [vec[0], vec[1]] loop_+=1 north = [vec[0]+1,vec[1]]; #print 'edge(north): ', edges[north[0], north[1]]; east = [vec[0], vec[1] +1]; #print 'edge(east): ', edges[east[0], east[1]]; south = [vec[0]-1,vec[1]]; #print 'edge(south): ', edges[south[0], south[1]]; west = [vec[0], vec[1] -1]; #print 'edge(west): ', edges[west[0], west[1]]; ne = [vec[0]+1,vec[1]+1] se = [vec[0]-1, vec[1] +1] sw = [vec[0]-1,vec[1]-1] nw = [vec[0]+1, vec[1] -1] traced_edge[vec[0], vec[1]] = 1; #Add current point to stack # print 'vec B4: ', (vec[1], vec[0]) vec_outline.AddPoint((vec[1], vec[0])) # break if edges[north[0], north[1]] >= 1: vec = north; edges[north[0], north[1]] = -1; #print 'north'; check_starting_point = 1; elif edges[east[0], east[1]] >= 1: vec = east; edges[east[0], east[1]] = -1; #print 'east'; check_starting_point = 1; elif edges[south[0], south[1]] >= 1: vec = south; edges[south[0], south[1]] = -1; #print 'south'; check_starting_point = 1; elif edges[west[0], west[1]] >= 1: vec = west; edges[west[0], west[1]] = -1; #print 'west'; check_starting_point = 1; elif edges[ne[0], ne[1]] >= 1: vec = ne; edges[ne[0], ne[1]] = -1; #print 'ne'; check_starting_point = 1; elif edges[se[0], se[1]] >= 1: vec = se; edges[se[0], se[1]] = -1; #print 'se'; check_starting_point = 1; elif edges[sw[0], sw[1]] >= 1: vec = sw; edges[sw[0], sw[1]] = -1; #print 'sw'; check_starting_point = 1; elif edges[nw[0], nw[1]] >= 1: vec = nw; edges[nw[0], nw[1]] = -1; #print 'nw'; check_starting_point = 1; size_ = vec_outline.GetNbrOfPoints() # Check if next position is on trace if traced_edge[vec[0], vec[1]] >= 1: print 'Found starting point! ', vec print '@loop:', loop_, ' the size (after tracing) is: ', size_ continue_ = 0 elif size_ == previous_size_: print 'Size if tracing vector is frozen at: ', vec print '@loop:', loop_, ' the size (after tracing) is: ', size_ print 'Breaking loop' continue_ = 0 previous_size_ = size_ # vv = [vec, vec1] # for x in range(vec[:,0]) # print vec # b[d] = 1 #Check for concavity ------------------------------------------------------- print '***Check concavity***' # print 'x: ', vec_outline.GetPoints_1Dim('x') # print 'first dim: ', vec_outline.GetDimensions()[0].GetName() vec = array(vec_outline.GetPoints_nDim(('y', 'x'))) # print 'test vec: ', vec # print 'vec2 test: ', vec2 # print len(vec) mem = zeros_like(a).astype(float) step_length = pixelStep isConcavity = 0 newConcavity = 0 all_Concavities = [] #Vector to store all concavities as homemade vector class appendVector = 1 # step_length = 25 currentConcavity = vut.Vector() #Workvariable for current vector, to be added to all_Concavities. Set to null when new vector found currentConcavity.SetName('con_000') #Initialize will be overwritten for i in range(step_length,(len(vec) - step_length)): # print 'index: ', i # print 'vec: ', vec[i] # print 'vec+: ', vec[i+step_length] # print 'vec-: ', vec[i-step_length] v1 = array(vec[i+step_length] - vec[i]) v2 = array(vec[i] - vec[i-step_length]) # print v1 # print v2 # dot_ = abs(dot(v1,(-1)*v2)) # print dot_ if abs(cross(v1,-v2)) <> 0: sign_cross = cross(v1,-v2)/abs(cross(v1,-v2)) # print sign_cross dot_product = abs(dot(v1,(-1)*v2)) if sign_cross == -1: if isConcavity == 0: #Enter new concavity newConcavity = 1 isConcavity = 1 if newConcavity == 1: # Check for 8-connectivity with existing vectors # print len(all_Concavities) for v in range(len(all_Concavities)): # test = all_Concavities[v].Is8Connected([vec[i][1], vec[i][0]]) if all_Concavities[v].Is8Connected('x', vec[i][1], 'y', vec[i][0]) == 1: currentConcavity = all_Concavities[v] # print 'Continuing vector: ', currentConcavity appendVector = 0 newConcavity = 0 if newConcavity == 1: #We have not found an existing vector to append to prev_name = currentConcavity.GetName() currentConcavity = vut.Vector() currentConcavity.SetName('con_' + pad_string(int(prev_name[-nbrOfIndexSpaces:]) + 1)) currentConcavity.AddDimension('x') currentConcavity.AddDimension('y') currentConcavity.AddDimension('value') # currentConcavity.AddDimension('active') # To turn off paired concavities in filtering # print 'Found new concavity at [y,x]: ', vec[i] appendVector = 1 newConcavity = 0 mem[vec[i][0], vec[i][1]] = 1 # mem[vec[i][0], vec[i][1]] = dot_product currentConcavity.AddPoint(([vec[i][1],vec[i][0],dot_product])) # print 'Adding point: x: ', [vec[i][1], ' y: ', vec[i][0], 'value: ', dot_product] else: if isConcavity == 1: #Exit concavity # print 'Exit concavity at: ', vec[i] if appendVector == 1: #Do not append if we are continuing an old vector all_Concavities.append(currentConcavity) isConcavity = 0 # Filter out all straight and lonely segments will get rid of most false concavities-------------------- print '***Filtering***' print 'Number of concavities found: ', len(all_Concavities) new_all_Concavities = [] for i in range(len(all_Concavities)): if all_Concavities[i].GetNbrOfPoints() > 2 and all_Concavities[i].IsStraight('y', 'x') == 0: new_all_Concavities.append(all_Concavities[i]) all_Concavities = new_all_Concavities print 'Number of concavities after filtering: ', len(all_Concavities) # for i in range(len(all_Concavities)): # print all_Concavities[i].GetName() #Rescale image ----------------------------------------------------------------- print '***Rescaling***' mem2 = zeros_like(a).astype(float) for i in range(len(all_Concavities)): # print all_Concavities[i].GetPoints('value') maximum = all_Concavities[i].Max('value') # print 'Maximum: ', maximum # pointsX = all_Concavities[i].GetPoints_nDim(('x')) pointsXY = all_Concavities[i].GetPoints_nDim(('x', 'y')) # pointsYX = all_Concavities[i].GetPoints_nDim(('y', 'x')) # print 'Points x is: ', pointsX # print 'Points xy is: ', pointsXY # print 'Points yx is: ', pointsYX # pointsY = all_Concavities[i].GetPoints_1Dim('y') # pointsVal = all_Concavities[i].GetPoints_1Dim('value') # print 'initial value: ', all_Concavities[i].GetPoints('value') for p in range(len(pointsXY)): unNormalizedValue = float(all_Concavities[i].GetPoints_1Dim('value')[p]) # print 'unNormalizedValue: ', unNormalizedValue normalizedValue = unNormalizedValue/maximum # print 'normalizedValue: ', normalizedValue all_Concavities[i].SetPoint('value', p, normalizedValue) mem2[pointsXY[p][1], pointsXY[p][0]] = normalizedValue # print 'After rescaling: ', all_Concavities[i].GetPoints_1Dim('value') # print 'Dim: ', mem.shape # print 'Max: ', mem.max() # print 'Min: ', mem.min() # mem = (mem/(mem.max()-mem.min())) + mem.min() # print 'Max: ', mem.max() # print 'Min: ', mem.min() # Mark minimum of each concavity (hopefully central point)--------------------------------- print '***Find center***' corners = zeros_like(a).astype(float) corners = where(traced_edge == 1, 0.2, 0) vec_corners = [] gradients = [] for i in range(len(all_Concavities)): print all_Concavities[i].GetPoints_1Dim('value') minimum = all_Concavities[i].Min('value') # print 'Minimum: ', minimum #Select only center point findCenter_points = all_Concavities[i].GetAllPointsWithValue('value', minimum) #Draw gradient from all points # findCenter_points = all_Concavities[i].GetAllPoints() # print 'Points: ', findCenter_points # print 'Length: ', len(findCenter_points) # if len(findCenter_points) == all_Concavities[i].GetNbrOfPoints: # print 'All minimum' # Several minimum: sort out the middle one if len(findCenter_points) > 1: print 'Several minimum found: ' total_mean = 0 for h in range(len(findCenter_points)): total_mean = total_mean + findCenter_points[h][0] print findCenter_points[h][0] mean = round(total_mean/(len(findCenter_points))) diff_smallest = 100 chosen_point = findCenter_points[0][0] # Choose first point as default for h in range(len(findCenter_points)): mean_diff = mean - findCenter_points[h][0] # print 'Mean diff: ', mean_diff # print 'Diff smallest: ', diff_smallest if abs(mean_diff) < abs(diff_smallest): diff_smallest = mean_diff chosen_point = findCenter_points[h] # chosen_point = uint8(mean - mean_diff) print 'Middle minimum is: ', chosen_point findCenter_points = [chosen_point] print 'Middle minimum len is: ', len(findCenter_points) for j in range(len(findCenter_points)): # Mark gradient in these points myIndex = self.GetPointIndex(vec_outline, findCenter_points[j][1][0], findCenter_points[j][1][1]) # grad = all_Concavities[i].ComputeCurvatureGradient(findCenter_points[j][0], pixelStep) grad = vec_outline.ComputeCurvatureGradient(myIndex, pixelStep, 1) newPoint = array([findCenter_points[j][1][0] + 50*grad[0], findCenter_points[j][1][1] + 50*grad[1]]).astype(int) gradients.append([[findCenter_points[j][1][0],newPoint[0]], [findCenter_points[j][1][1],newPoint[1]]]) newCorner = vut.Vector() newCorner.AddDimension('parent') newCorner.AddDimension('x') newCorner.AddDimension('y') newCorner.AddDimension('grad_x') newCorner.AddDimension('grad_y') newCorner.AddDimension('certainty') #How many possible corner points do we have in this concavity? can be only one parentIndex = int(all_Concavities[i].GetName()[-3:]) newCorner.AddPoint((all_Concavities[i].GetName(), findCenter_points[j][1][0], findCenter_points[j][1][1], grad[0], grad[1], 1.0/len(findCenter_points))) newCorner.SetName('con_' + pad_string(parentIndex) + '_cor_' + pad_string(j + 1)) vec_corners.append(newCorner) #corners[findCenter_points[j][1][1], findCenter_points[j][1][0]] = 0.7 #Draw corners directly on image print 'Number of corners found: ', len(vec_corners) #for i in range(len(vec_corners)): # print vec_corners[i].GetCompletePoint(0) # Draw rays------------------------------------------------------------------- print '***Drawing lines***' # intersections = [] # Vector to keep full scale matrices - one for each corner/ray vec_intersections = [] #Vector for all intersections for i in range(len(vec_corners)): x0 = vec_corners[i].GetPoints_1Dim('x')[0] y0 = vec_corners[i].GetPoints_1Dim('y')[0] #print 'initial point: [', x0, ',', y0, ']' # certainty0 = vec_corners[i].GetPoints_1Dim('certainty')[0] grad_x0 = vec_corners[i].GetPoints_1Dim('grad_x') #print 'grad_x0', grad_x0 grad_y0 = vec_corners[i].GetPoints_1Dim('grad_y') #print 'grad_y0', grad_y0 # Compute line eq if grad_x0[0] <> 0: k0 = (grad_y0[0]/grad_x0[0]) m0 = y0 - x0*k0 else: k0 = 'INF' m0 = x0 for j in range(i + 1, len(vec_corners)): x1 = vec_corners[j].GetPoints_1Dim('x')[0] y1 = vec_corners[j].GetPoints_1Dim('y')[0] #print 'second point: [', x1, ',', y1, ']' # certainty1 = vec_corners[j].GetPoints_1Dim('certainty')[0] grad_x1 = vec_corners[j].GetPoints_1Dim('grad_x') #print 'grad_x1', grad_x1 grad_y1 = vec_corners[j].GetPoints_1Dim('grad_y') #print 'grad_y1', grad_y1 # if grad_x1[0] <> 0: k1 = (grad_y1[0]/grad_x1[0]) m1 = y1 - x1*k1 else: k1 = 'INF' m1 = x1 intersect = vectorComputations.ComputeIntersection([k0,m0], [k1,m1]) intersect_name = vec_corners[i].GetName() + ' with ' + vec_corners[j].GetName() # if vec_outline.IsInside('x', intersect[0], 'y', intersect[1]): if intersect <> 'NULL': newIntersect = vut.Vector() con1 = vec_corners[i].GetName() con2 = vec_corners[i].GetName() if con1 == con2: print 'ERROR: Crossing with self' newIntersect.AddDimension('parent1') #corner newIntersect.AddDimension('parent2') #corner newIntersect.AddDimension('distance') # distance between corners newIntersect.AddDimension('intersect_x') newIntersect.AddDimension('intersect_y') newIntersect.AddDimension('certainty') #currently not in use cor_1 = [vec_corners[i].GetPoints_1Dim('x')[0], vec_corners[i].GetPoints_1Dim('y')[0]] cor_2 = [vec_corners[j].GetPoints_1Dim('x')[0], vec_corners[j].GetPoints_1Dim('y')[0]] distance = vectorComputations.ComputeDistance(cor_1, cor_2) print 'Distance: ', distance newIntersect.AddPoint((vec_corners[i].GetName(), vec_corners[j].GetName(), distance, intersect[0], intersect[1], 1.0)) newIntersect.SetName(intersect_name) vec_intersections.append(newIntersect) # intersect.append(intersect_name) # intersections.append(intersect) print 'Number of intersections found: ', len(vec_intersections) for i in range(len(vec_intersections)): print vec_intersections[i].GetName() # Filter intersections # filteredIntersections = [] vec_filteredIntersection = [] for i in range(len(vec_intersections)): # if intersections[i][0] == 260.0: if vec_outline.IsInside('x', vec_intersections[i].GetPoints_1Dim('intersect_x')[0], 'y', vec_intersections[i].GetPoints_1Dim('intersect_y')[0]): # filteredIntersections.append(intersections[i]) vec_filteredIntersection.append(vec_intersections[i]) # intersections = filteredIntersections vec_intersections = vec_filteredIntersection print 'Number of intersections after filtering: ', len(vec_intersections) for i in range(len(vec_intersections)): print vec_intersections[i].GetName() #corners[intersections[i][1], intersections[i][0]] = 1 #Print intersections directly on image # Pair intersections ---------------------------------------------------------- print '***Filtering intersections***' #THIS IS AS FAR AS WE HAVE DONE!!! # print 'All concavitiers: ', all_Concavities for i in range(len(vec_intersections)): print vec_intersections[i].GetName() print 'Parent 1 ', vec_intersections[i].GetPoints_1Dim('parent1') print 'Parent 2 ', vec_intersections[i].GetPoints_1Dim('parent2') print 'X ', vec_intersections[i].GetPoints_1Dim('intersect_x') print 'Y ', vec_intersections[i].GetPoints_1Dim('intersect_y') print 'Distance ', vec_intersections[i].GetPoints_1Dim('distance') for i in range(len(all_Concavities)): print all_Concavities[i].GetName() allowedConcavities = all_Concavities # Compute confidence matrix # Display figures -------------------------------------------------------------- print '***Printing result***' # Zoom if crop_: if image_: mem2 = mem2[300:400,200:300] mem = mem[300:400,200:300] # corners = corners[300:400,200:300] elif shapes_: # mem2 = mem2[150:250,150:250] mem2 = mem2[250:450,200:400] #Add handling for first 5 & last 5 # print mem.max() # print mem.min() black = zeros_like(a) if plot_all_figures_: fig1 = plt.figure() plot1 = fig1.add_subplot(111) plot1.set_title('Original') imshow(a, cmap='hot', origin='lower') fig2 = plt.figure() plot2 = fig2.add_subplot(111) plot2.set_title('Edge') imshow(edges, cmap='gray', origin='lower') fig4 = plt.figure() plot4 = fig4.add_subplot(111) plot4.set_title('Concavity cross product -1') imshow(mem, cmap='hot', origin='lower') fig5 = plt.figure() plot5 = fig5.add_subplot(111) plot5.set_title('After filtering (may be zoomed)') myplot = imshow(mem2, cmap='hot', origin='lower') fig5.colorbar(myplot, shrink=0.5, aspect=5) # trace2 = traced_edge[300:400,200:300] fig3 = plt.figure() plot3 = fig3.add_subplot(111) for i in range(len(gradients)): print gradients[i] plt.plot(gradients[i][0], gradients[i][1], linewidth=2.0, color='white') for i in range(vec_outline.GetNbrOfPoints()): plt.scatter(vec_outline.GetPoints_1Dim('x')[i], vec_outline.GetPoints_1Dim('y')[i], color = 'yellow') for i in range(len(vec_corners)): #print 'x: ', (vec_corners[i].GetPoints_1Dim('x')[0]) #print 'y: ', (vec_corners[i].GetPoints_1Dim('y')[0]) plt.scatter(vec_corners[i].GetPoints_1Dim('x')[0], vec_corners[i].GetPoints_1Dim('y')[0], color='red') # for i in range(len(vec_intersections)): #print intersections[i] #corners[intersections[i][1], intersections[i][0]] = 1 #Print intersections directly on image # plt.scatter(vec_intersections[i].GetPoints_1Dim('intersect_x')[0], vec_intersections[i].GetPoints_1Dim('intersect_y')[0], color='white') plot3.set_title('Trace with marked corners') imshow(black, cmap='hot', origin='lower') # fig6 = plt.figure() # plot6 = fig6.add_subplot(111) # plot6.set_title('Raypoint1') # imshow(all_Rays[1], cmap='hot', origin='lower') # imshow(a, cmap = cm.gray)# left plot in the image above plt.show()
def my_imfilter(image,filter): #which will work identically to the function below output = imfilter(image, filter) #replace your code here
print i, misc.imsave("out.png", filterfunc(misc.imread("out.png"))) try: w.extract(misc.imread("out.png")) except ReedSolomonError: return prev_i prev_i = i return prev_i if __name__ == "__main__": from scipy.ndimage.filters import gaussian_filter from skimage.filter import tv_denoise w = Watermarker(6, 3, 2394181, "bior3.3") out = w.embed(misc.imread("pics/lena.png"), "123456", 10) misc.imsave("out3.png", out) exit() #test_filter(w, out, lambda img, i: gaussian_filter(img, i / 10.0)) #test_filter(w, out, tv_denoise) #print test_recursive_filter(w, out, lambda img: misc.imfilter(img, "smooth")) for flt in [ "blur", "contour", "detail", "edge_enhance", "edge_enhance_more", "emboss", "find_edges", "smooth", "smooth_more", "sharpen" ]: print flt, print test_recursive_filter(w, out, lambda img: misc.imfilter(img, flt)) print
start_time = time.time() x, min_val, info = fmin_l_bfgs_b(evaluator.loss, x.flatten(), fprime=evaluator.grads, maxfun=20) if prev_min_val == 0: improvement = 0 else: improvement = (prev_min_val - min_val) / prev_min_val * 100 print("Current loss value:", min_val, " Improvement : %0.3f" % improvement, "%") prev_min_val = min_val # save current generated image img = deprocess_image(x.copy()) if not use_content_img: img = imfilter(img, ftype='smooth') img = imfilter(img, ftype='sharpen') if use_content_img and preserve_color and content is not None: img = original_color_transform(content, img) fname = target_img_prefix + '_at_iteration_%d.png' % (i + 1) imsave(fname, img) end_time = time.time() print('Image saved as', fname) print('Iteration %d completed in %ds' % (i + 1, end_time - start_time)) if args.min_improvement != 0.0: if improvement < args.min_improvement and i > 1: print("Script is early stopping since improvement (%0.2f) < min improvement (%0.2f)" % (improvement, args.min_improvement))
w.extract(misc.imread("out.png")) except ReedSolomonError: return prev_i prev_i = i return prev_i if __name__ == "__main__": from scipy.ndimage.filters import gaussian_filter from skimage.filter import tv_denoise w = Watermarker(6, 3, 2394181, "bior3.3") out = w.embed(misc.imread("pics/lena.png"), "123456", 10) misc.imsave("out3.png", out) exit() #test_filter(w, out, lambda img, i: gaussian_filter(img, i / 10.0)) #test_filter(w, out, tv_denoise) #print test_recursive_filter(w, out, lambda img: misc.imfilter(img, "smooth")) for flt in ["blur", "contour", "detail", "edge_enhance", "edge_enhance_more", "emboss", "find_edges", "smooth", "smooth_more", "sharpen"]: print flt, print test_recursive_filter(w, out, lambda img: misc.imfilter(img, flt)) print
def sharpen(im, level): level = level.upper() intensity = {'HIGH': 3, 'MEDIUM': 2, "LOW": 1} for j in range(intensity[level]): im = misc.imfilter(im, 'sharpen') return im
maxfun=20) if prev_min_val == 0: improvement = 0 else: improvement = (prev_min_val - min_val) / prev_min_val * 100 print("Current loss value:", min_val, " Improvement : %0.3f" % improvement, "%") prev_min_val = min_val # save current generated image img = deprocess_image(x.copy()) if not use_content_img: img = imfilter(img, ftype='smooth') img = imfilter(img, ftype='sharpen') if use_content_img and preserve_color and content is not None: img = original_color_transform(content, img) fname = target_img_prefix + '_at_iteration_%d.png' % (i + 1) imsave(fname, img) end_time = time.time() print('Image saved as', fname) print('Iteration %d completed in %ds' % (i + 1, end_time - start_time)) if args.min_improvement != 0.0: if improvement < args.min_improvement and i > 1: print( "Script is early stopping since improvement (%0.2f) < min improvement (%0.2f)"
def sharpen(self): self.canvas_data = misc.imfilter(self.canvas_data, ftype='sharpen') self.draw_canvas()