def morph(rutaImgOrigen, rutaImgDestino, rutaArchivoLineas, N): #ruta del archivo que contiene los pares de lineas de ref rutaArchivoDeLineas = "../txt/refLines.txt" archivoDeLineas = open(rutaArchivoDeLineas, 'r') lineas = archivoDeLineas.read().splitlines() #imagen origen imgOrigen = pai_io.imread(rutaImgOrigen) #imagen destino imgDestino = pai_io.imread(rutaImgDestino) #dimensiones de la imagen que se obtendrá largo, ancho, dim = imgDestino.shape imageB = np.zeros((imgDestino.shape), np.uint8) paresDeLineas = [] for par in lineas: L = par[3:].split(",") for i in range(len(L)): L[i] = int(L[i]) paresDeLineas.append(L) listaPuntos = [] for lineas in paresDeLineas: for i in range(len(lineas)): if i % 2 == 0: P = [] P.append(lineas[i]) else: P.append(lineas[i]) listaPuntos.append(P) listaPuntos = np.array(listaPuntos) warp(img)
def helo_histogram(image_path, B, K): image = pai_io.imread(image_path, as_gray=True) #matriz que representa la imagen L_x = np.zeros((B, B)) #conjunto de gradientes locales c/r a x L_y = np.zeros((B, B)) #conjunto de gradientes locales c/r a y ang = np.zeros((B, B)) kernel_x = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]]) kernel_y = np.transpose(kernel_x) g_x = nd_filters.convolve(image, kernel_x, mode='constant', cval=0.0) g_y = nd_filters.convolve(image, kernel_y, mode='constant', cval=0.0) height = np.shape(image)[0] #nro de pixeles de largo width = np.shape(image)[1] #nro de pixeles de ancho for i in range(height): for j in range(width): r = round((i / height) * (B - 1)) s = round((j / width) * (B - 1)) #print(i, j) L_x[r][s] += (g_x[i][j])**2 - (g_y[i][j])**2 L_y[r][s] += 2 * (g_x[i][j]) * (g_y[i][j]) for r in range(B): for s in range(B): ang[r, s] = np.arctan2(L_y[r, s], L_x[r, s]) * 0.5 - np.pi * 0.5 ho.getHistogram(ang, K)
def calculate_all_fingerprints_histograms(local_orientation_function, K, L): print('Getting local orientation database using function: {}'.format( local_orientation_function.__name__)) try: with open(local_orientation_function.__name__ + '.pkl', 'rb') as input: finger_orientations = pickle.load(input) except (IOError, pickle.PickleError): finger_orientations = {} if K in finger_orientations: print('Local orientations cache loaded for K = {}'.format(K)) finger_orientations_k = finger_orientations[K] else: print('Local orientations cache not found') print( 'Generating local orientations database for K = {}, takes a few minutes' .format(K)) finger_orientations_k = {} pathlist = Path('./fingerprints').rglob('*.png') for path in pathlist: image = pai_io.imread(str(path), as_gray=True) print('Processing file: {}'.format(str(path))) ang_local, r_local = local_orientation_function(image, K) finger_orientations_k[str(path)] = (ang_local, r_local) finger_orientations[K] = finger_orientations_k with open(local_orientation_function.__name__ + '.pkl', 'wb') as output: print('Saving local orientations cache') pickle.dump(finger_orientations, output, pickle.HIGHEST_PROTOCOL) finger_histograms = {} print('Generating histograms for L = {}'.format(L)) for filename in finger_orientations_k: ang_local, r_local = finger_orientations_k[filename] finger_histograms[filename] = oh.compute_orientation_histogram_lineal( ang_local, r_local, L) return finger_histograms
def encode(image_file, text, bits): img = pai_io.imread(image_file) ext = len(image_file) - image_file[::-1].index('.') - 1 is_color = len(img.shape) == 3 dec = decodifier.Decodifier(img, is_color, bits) pai_io.imsave(image_file[:ext] + '_out' + image_file[ext:], dec.encode(text.read()))
def getHistogram(image, K): if (type(image) == np.ndarray): hA = oh.compute_orientation_histogram(image, K) plt.bar(range(K), height=hA) plt.show() else: img = pai_io.imread(image, as_gray=True) hA = oh.compute_orientation_histogram(img, K) plt.bar(range(K), height=hA) plt.show()
def decode(image_file): img = pai_io.imread(image_file) is_color = len(img.shape) == 3 if is_color: nbits = (img[0][0][0] & 7) + 1 else: nbits = (img[0][0] & 7) + 1 dec = decodifier.Decodifier(img, is_color, nbits) print(dec.decode())
def shelo_histogram(image, B, K): img = pai_io.imread(image, as_gray=True) filas = np.shape(img)[0] columnas = np.shape(img)[1] L_x = np.zeros((B,B)) #conjunto de gradientes locales c/r a x L_y = np.zeros((B,B)) #conjunto de gradientes locales c/r a y ang = np.zeros((B,B)) kernel_x = np.array([[-1,0,1], [-2,0,2],[-1,0,1]]) kernel_y = np.transpose(kernel_x) g_x = nd_filters.convolve(image, kernel_x, mode = 'constant', cval = 0.0) g_y = nd_filters.convolve(image, kernel_y, mode = 'constant', cval = 0.0) for i in range(filas): for j in range(columnas): return 0
import matplotlib.pyplot as plt import numpy as np import basis import pai_io import orientation_histograms as oh delfin = '/home/nenjamib/Escritorio/Primavera 2019/Procesamiento y Analisis de Imagenes/Tareas/cc5508-tareas/T2/dataset_1/BD_2/dolphin/240003.jpg' # print(type(delfin)) delfin2 = pai_io.imread(delfin, as_gray=True) # print(type(delfin2)) # print(type(delfin2) == np.ndarray) """ Histrograma de Orientaciones Esta funcion recibe el path o la matriz correspondiente a la imagen y un valor de cuantizacion, y devuelve el histograma de orientaciones correspondiente (HO) Parametros ---------- image_path: path o matriz de la imagen K: valor de cuantizacion """ def getHistogram(image, K): if (type(image) == np.ndarray): hA = oh.compute_orientation_histogram(image, K) plt.bar(range(K), height=hA) plt.show() else: img = pai_io.imread(image, as_gray=True) hA = oh.compute_orientation_histogram(img, K)
''' Created on Aug 6, 2019 @author: jsaavedr Filtro Mediana ''' import matplotlib.pyplot as plt import skimage.filters as filters import skimage.morphology as morphology import scipy.ndimage.filters as nd_filters import basis import pai_io if __name__ == '__main__' : filename ='../images/gray/ruido.tif' image=pai_io.imread(filename, as_gray = True) strel=morphology.square(3) image_median=filters.median(image, strel) g_kernel = basis.get_gaussian2d(2, 6) image_g = nd_filters.convolve(image, g_kernel, mode='constant', cval=0) fig, xs = plt.subplots(1,3) for i in range(3): xs[i].set_axis_off() xs[0].imshow(image, cmap = 'gray', vmin = 0, vmax = 255) xs[0].set_title('Image') xs[1].imshow(image_g, cmap = 'gray', vmin = 0, vmax = 255) xs[1].set_title('Filtro Gaussiano') xs[2].imshow(image_median, cmap = 'gray', vmin = 0, vmax = 255) xs[2].set_title('Filtro Mediana') plt.show()
if __name__ == '__main__': parser = argparse.ArgumentParser( description='Hide an image inside another.') parser.add_argument('-imageA', type=str, help='Image that hides another', required=True) parser.add_argument('-imageB', type=str, help='Image that is hidden', required=True) parser.add_argument('-b', type=np.uint8, help='Amount of bits to hide') args = parser.parse_args() image_A = pai_io.imread(args.imageA) image_B = pai_io.imread(args.imageB) image_A, image_B = match_images_dimensions(image_A, image_B) output = None bits_to_hide = args.b if bits_to_hide is None: max_capacity = int(np.ceil(get_max_bit_size(image_A) * 3.0 / 8.0)) bits_to_hide = get_max_bit_size(image_B) if bits_to_hide > max_capacity: raise ValueError("imageB size exceeds imageA's capacity to hide") output = hide_image(image_A, image_B, bits_to_hide, 0) else: max_b_size = get_max_bit_size(image_B) if bits_to_hide > max_b_size: raise ValueError( "b parameter larger than imageB's most significant bit")
import pai_io img = pai_io.imread("_lion_gray_out.jpg") print("{}, ".format(img[0]))
def draw_all_lbbs(image, ccs, box_rgb_color): for cc in ccs: y, x, h, w = cc['bbox'] for i in range(y, y + h): image[i, x] = box_rgb_color image[i, x + w] = box_rgb_color for j in range(x, x + w): image[y, j] = box_rgb_color image[y + h, j] = box_rgb_color return image if __name__ == '__main__': if len(sys.argv) != 2: raise SyntaxError('usage: yellow_circles.py [path to image]') input_image = imread(sys.argv[1]) yellow = get_yellow(input_image) yellow_binary = threshold(yellow, get_threshold_otsu(yellow)) imsave( 'yellow_binary.png', np.interp(yellow_binary, (yellow_binary.min(), yellow_binary.max()), (0, 255)).astype(np.uint8)) yellow_ccs = get_ccomponents(yellow_binary) yellow_ccs = remove_small_components(yellow_ccs, 50) with open('yellow_ccs.txt', 'w') as f: for cc in yellow_ccs: write_cc(cc, f) yellow_ccs = [add_error_to_circle(cc) for cc in yellow_ccs] yellow_circle_ccs = filter_by_error(yellow_ccs, 0.1) image_with_boxes = draw_all_lbbs(input_image, yellow_circle_ccs, (255, 0, 0))
import sys sys.path.append('../pai_basis') import basis import pai_io import orientation_histograms as oh import matplotlib.pyplot as plt import numpy as np if __name__ == '__main__': #filename = '../images/gray/im_34.png' #filename = '../images/gray/im_2.tif' filenameA = '../images/gray/elephant.jpg' filenameB = '/home/jsaavedr/Documents/Datasets/SBIR/dataset_1/BD_2/chair/180016.jpg' imageA = pai_io.imread(filenameA, as_gray=True) imageB = pai_io.imread(filenameB, as_gray=True) K = 36 hA = oh.compute_orientation_histogram(imageA, K) hB = oh.compute_orientation_histogram(imageB, K) distancia = np.sqrt(np.sum(np.square(hA - hB))) print('distancia = {}'.format(distancia)) fig, xs = plt.subplots(2, 2) xs[0, 0].imshow(imageA, cmap='gray') xs[0, 1].bar(range(K), height=hA) xs[1, 0].imshow(imageB, cmap='gray') xs[1, 1].bar(range(K), height=hB) plt.show()
import argparse import matplotlib.pyplot as plt import numpy as np import orientation_histograms as oh import pai_io import time if __name__ == '__main__': parser = argparse.ArgumentParser(description='Plots local orientations.') parser.add_argument('-image', type=str, help='Image to calculate local orientations.', required=True) parser.add_argument('-k', type=int, help='Grid dimensions.', required=True) args = parser.parse_args() image = pai_io.imread(args.image, as_gray=True) K = args.k print('Generating local orientations without bilinear interpolation') start = time.time() A1, R1 = oh.compute_local_orientations_basic(image, K) end = time.time() print('Function took {} sec'.format(end - start)) print('Generating local orientations with bilinear interpolation') start = time.time() A2, R2 = oh.compute_local_orientations_bilinear(image, K) end = time.time() print('Function took {} sec'.format(end - start)) ys = np.arange(K) xs = np.arange(K) ys = np.floor(((ys + 0.5) / K) * image.shape[0]) xs = np.floor(((xs + 0.5) / K) * image.shape[1])
import matplotlib.pyplot as plt import pai_io import sys def get_bits_hidden_value(image): if len(image.shape) == 2: return image[0][0] else: return image[0][0][0] def unhide_image(image, bits_hidden): return image << (8 - bits_hidden) if __name__ == '__main__': if len(sys.argv) != 2: raise SyntaxError('usage: unhide.py [path to image]') input_image = pai_io.imread(sys.argv[1]) bits_hidden = get_bits_hidden_value(input_image) output = unhide_image(input_image, bits_hidden) pai_io.imsave('unhidden.png', output) plt.imshow(output) plt.axis('off') plt.show()
''' Created on Aug 1, 2019 @author: jsaavedr Image Histogram ''' import numpy as np import matplotlib.pyplot as plt import pai_io import utils if __name__ == '__main__': filename = '../images/gray/ten_coins.png' image = pai_io.imread(filename) #image = np.zeros((400,400), dtype = np.uint8) #image[100:170, 200:270] = 255 h = utils.get_histogram(image) fig, xs = plt.subplots(1, 2) xs[0].set_axis_off() xs[0].imshow(image, cmap='gray', vmin=0, vmax=255) xs[1].bar(x=np.arange(256), height=h) plt.show()
recover_error_bilinear = calculate_recover_error( oh.compute_local_orientations_bilinear) print('Recover error without bilinear interpolation: ' + str(recover_error_regular)) print('Recover error with bilinear interpolation: ' + str(recover_error_bilinear)) else: if args.basic: print('Calculating best 5 matches without bilinear interpolation') local_orientation_function = oh.compute_local_orientations_basic else: print('Calculating best 5 matches with bilinear interpolation') local_orientation_function = oh.compute_local_orientations_bilinear finger_histograms = calculate_all_fingerprints_histograms( local_orientation_function, args.k, args.l) image = pai_io.imread(args.image, as_gray=True) ang_local, r_local = local_orientation_function(image, args.k) print('Generating histogram for input, takes a few seconds') input_histogram = oh.compute_orientation_histogram_lineal( ang_local, r_local, args.l) results = get_top_5_histogram_matches(input_histogram, finger_histograms, False) print('Showing results') image1 = pai_io.imread(results[0][0], as_gray=True) image2 = pai_io.imread(results[1][0], as_gray=True) image3 = pai_io.imread(results[2][0], as_gray=True) image4 = pai_io.imread(results[3][0], as_gray=True) image5 = pai_io.imread(results[4][0], as_gray=True) fig, axes = plt.subplots(nrows=2, ncols=5, figsize=(10, 5)) axes[0][0].axis('off') axes[0][1].axis('off')