def task3(): nasa_matrix = normalize_intensity(imread(NASA)) flatfield_matrix = normalize_intensity(imread(FLATFIELD)) corrected_image = correct_with_flatfield(nasa_matrix, flatfield_matrix) output_path = os.path.join(OUTPUT_DIR, os.path.split(NASA)[-1]) imsave(output_path, corrected_image) pl.imshow(corrected_image, cmap=cm.Greys_r) pl.show()
def task3_1(): print('3.1') c_img = normalize_intensity(imread(CAMERAMAN)) fft_res = fft2(a=c_img) output_path = os.path.join(OUTPUT_DIR, "3_1_fft_spectrum_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, log(1 + abs(fftshift(fft_res)))) b_img = normalize_intensity(imread(BRICKS)) fft_res = fft2(a=b_img) output_path = os.path.join(OUTPUT_DIR, "3_1_fft_spectrum_" + os.path.split(BRICKS)[-1]) imsave(output_path, log(1 + abs(fftshift(fft_res))))
def task3_2(): print('3.2') low_pass = normalize_intensity(imread(LOW_PASS)) high_pass = normalize_intensity(imread(HIGH_PASS)) img_freq_dom = fft2(a=normalize_intensity(imread(BRICKS_2))) apply_low_pass = img_freq_dom * low_pass ifft_res = ifft2(a=apply_low_pass) output_path = os.path.join(OUTPUT_DIR, "3_2_low_pass_" + os.path.split(BRICKS_2)[-1]) imsave(output_path, abs(ifft_res)) apply_high_pass = img_freq_dom * high_pass ifft_res = ifft2(a=apply_high_pass) output_path = os.path.join(OUTPUT_DIR, "3_2_high_pass_" + os.path.split(BRICKS_2)[-1]) imsave(output_path, abs(ifft_res))
def load(self): self.array = [] for path in self.paths.order_by('z'): array = imread(path.url()) self.array.append(array) self.array = np.dstack(self.array).squeeze() # remove unnecessary dimensions return self.array
def __getitem__(self,n,_cached=np.array(-1)): """Return image n in the queue. Loading is done on demand. Input: ------ n : int Number of image required. Output: ------- img : array Image #n in the collection. """ idx = n % len(self.data) if (_cached != n and self.conserve_memory) or (self.data[idx] is None): try: image_data = imread(self.files[n], self.grey) except IOError: raise IOError('Could not read the file %s.' % self.files[n]) with file(self.files[n]) as f: print f exif = EXIF.process_file(f) self.data[idx] = Image(image_data, filename=os.path.basename(self.files[n]), EXIF=exif,info={}) _cached.flat = n return self.data[idx]
def read_pair_of_images(image1,image2, crop_vector, itt, spc): """ Returns two matrices of intensity values of a pair of PIV images """ import scipy.misc.pilutil as im A = im.imread(image1,1)/255.0 B = im.imread(image2,1)/255.0 sxa,sya = A.shape sxb,syb = B.shape sx = min(sxa,sxb) sy = min(sya,syb) l,t,r,b = crop_vector[:] # left, right, top, bottom Number of lines to crop, each of SPC pixels A = A[0+t*itt:spc*(sx/spc)-b*itt,0+l*itt:spc*(sy/spc)-r*itt] B = B[0+t*itt:spc*(sx/spc)-b*itt,0+l*itt:spc*(sy/spc)-r*itt] return A,B
def task2_2(): print('2.2') img = normalize_intensity(imread(CAMERAMAN)) gaussian = gaussian_noise(img, mean=0, std=0.1) peppered = salt_and_pepper_noise(img, density=0.25) output_path = os.path.join(OUTPUT_DIR, "2_2_gauss_med_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, median_mask(gaussian, filter_size=5)) output_path = os.path.join(OUTPUT_DIR, "2_2_pepper_med_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, median_mask(peppered, filter_size=5))
def task4_1(): einstein_matrix = imread(EINSTEIN) corrected = gamma_correct(einstein_matrix, gamma=1.5) output_path = os.path.join(OUTPUT_DIR, "gamma_" + os.path.split(EINSTEIN)[-1]) imsave(output_path, corrected) stretched = stretch_range(einstein_matrix) corrected = gamma_correct(stretched, gamma=1.5) output_path = os.path.join(OUTPUT_DIR, "stretched_gamma_" + os.path.split(EINSTEIN)[-1]) imsave(output_path, corrected)
def OnBtnRenderButton(self, event): self.logger.info("IMG_FRAME starting OnBtnRenderButton") mycur = self.GetCursor(); self.txtOutputFile.SetValue("") self.SetCursor(wx.StockCursor(id=wx.CURSOR_WAIT)) localBmp = wx.BitmapFromImage(self.imgScaled) sDtFrom = self.dateFrom.GetValue().Format('%Y-%m-%d') sDtTo = self.dateTo.GetValue().Format('%Y-%m-%d') sHHFrom = "00" sMMFrom = "00" sSSFrom = "00" sHHTo = "23" sMMTo = "59" sSSTo = "59" sDtFrom = "%s %s:%s:%s.000000" % (sDtFrom,sHHFrom,sMMFrom,sSSFrom) sDtTo = "%s %s:%s:%s.000000" % (sDtTo,sHHTo,sMMTo,sSSTo) dtf=datetime.strptime(sDtFrom,"%Y-%m-%d %H:%M:%S.%f") dtt=datetime.strptime(sDtTo,"%Y-%m-%d %H:%M:%S.%f") sAt_from = dtf.strftime('%Y%m%d%H%M%S%f') sAt_to = dtt.strftime('%Y%m%d%H%M%S%f') self.imgFileName = self.imgFileName img = imread(self.imgFilePath) img_shape=img.shape delta = 1.0 x = np.arange(0, img_shape[1], delta) y = np.arange(0, img_shape[0], delta) yj=img_shape[0]+1 #1201 601 xj=img_shape[1]+1 #1601 801 W = float(img_shape[1]) H = float(img_shape[0]) FW = W / float(800) FH = H / float(600) gx, gy = np.mgrid[0:xj, 0:yj] mysensors = np.zeros((0,2)) myvalues = np.zeros(0,'f') rowList = self.LoadDatapoints(self.imgFileName,sAt_from, sAt_to) for row in rowList: at_val = float(row[3]) const = float(row[4]) #constant_value lambda_val = float(row[5]) #lambda_value first = float(row[6]) #factor_value second = float(row[7]) #factor_value_2 sFormula = row[8] delta_val = at_val - lambda_val x = delta_val #resVal = second*x*x + first*x + const try: retVal = eval(sFormula) except Exception, e: retVal = 0.0 self.logger.info("Exception on eval(%s): %s" % (sFormula, str(e))) mysensors = np.append(mysensors,[[FW*row[1],H-FH*row[2]]],axis=0) #mysensors = np.append(mysensors,[[row[1],600-row[2]]],axis=0) myvalues = np.append(myvalues,[retVal],axis=0)
def PrintColorMap(dateFrom, dateTo, sOutDir, imgFilePath, imgFileName, sMethod): # print "PrintColorMap-1" sDtFrom = dateFrom.strftime("%Y-%m-%d") sDtTo = dateTo.strftime("%Y-%m-%d") sHHFrom = "00" sMMFrom = "00" sSSFrom = "00" sHHTo = "23" sMMTo = "59" sSSTo = "59" sDtFrom = "%s %s:%s:%s.000000" % (sDtFrom, sHHFrom, sMMFrom, sSSFrom) sDtTo = "%s %s:%s:%s.000000" % (sDtTo, sHHTo, sMMTo, sSSTo) dtf = datetime.strptime(sDtFrom, "%Y-%m-%d %H:%M:%S.%f") dtt = datetime.strptime(sDtTo, "%Y-%m-%d %H:%M:%S.%f") sAt_from = dtf.strftime("%Y%m%d%H%M%S%f") sAt_to = dtt.strftime("%Y%m%d%H%M%S%f") img = imread(imgFilePath) img_shape = img.shape delta = 1.0 x = np.arange(0, img_shape[1], delta) y = np.arange(0, img_shape[0], delta) yj = img_shape[0] + 1 xj = img_shape[1] + 1 W = float(img_shape[1]) H = float(img_shape[0]) FW = W / float(800) FH = H / float(600) gx, gy = np.mgrid[0:xj, 0:yj] mysensors = np.zeros((0, 2)) myvalues = np.zeros(0, "f") # print "PrintColorMap-2 before LoadDatapoints" rowList = LoadDatapoints(imgFileName, sAt_from, sAt_to) for row in rowList: at_val = float(row["avg_value_at"]) const = float(row["constant_value"]) # constant_value lambda_val = float(row["lambda_value"]) # lambda_value first = float(row["factor_value"]) # factor_value second = float(row["factor_value_2"]) # factor_value_2 sFormula = row["ds_formula"] delta_val = at_val - lambda_val x = delta_val try: retVal = eval(sFormula) except Exception, e: retVal = 0.0 logger.error("PrintColorMap Exception on eval for %s: error message is '%s'" % (imgFileName, str(e))) mysensors = np.append(mysensors, [[FW * row["px"], H - FH * row["py"]]], axis=0) myvalues = np.append(myvalues, [retVal], axis=0)
def task2_3(): print('2.3') img = normalize_intensity(imread(BRICKS)) a_img = alias(img, 4) output_path = os.path.join(OUTPUT_DIR, "2_3_downscaled_no_filter_" + os.path.split(BRICKS)[-1]) imsave(output_path, a_img) gfilter_img = gauss_filter(img, 0.8) agf_img = alias(gfilter_img, 4) output_path = os.path.join(OUTPUT_DIR, "2_3_gauss_8_" + os.path.split(BRICKS)[-1]) imsave(output_path, agf_img) gfilter_img = gauss_filter(img, 0.4) agf_img = alias(gfilter_img, 4) output_path = os.path.join(OUTPUT_DIR, "2_3_gauss_4_" + os.path.split(BRICKS)[-1]) imsave(output_path, agf_img)
def makenparrayfromfile(fimgfilename, wsselectionBox, uniqueExtension): fimgpilopen = Image.open(fimgfilename) fimgcropped = fimgpilopen.crop(wsselectionBox) fimgcropped.save('/dev/shm/'+uniqueExtension+'nuvolatools-proctemppngtimgfilecrop.png','PNG') fimggray = imread('/dev/shm/'+uniqueExtension+'nuvolatools-proctemppngtimgfilecrop.png', flatten = True) #print dir(imggray) print "flattening pil image" pdb.gimp_progress_set_text('flattening pil image') fbimggray = np.uint8(fimggray) print "flattened" fimg = np.asarray(fbimggray) print "array created" return fimg
def task2_1(): print('2.1') img = normalize_intensity(imread(CAMERAMAN)) gaussian = gaussian_noise(img, mean=0, std=0.1) output_path = os.path.join(OUTPUT_DIR, "2_1_gauss_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, gaussian) peppered = salt_and_pepper_noise(img, density=0.25) output_path = os.path.join(OUTPUT_DIR, "2_1_pepper_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, peppered) output_path = os.path.join(OUTPUT_DIR, "2_1_gauss_avg_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, averaging_mask(gaussian, filter_size=5)) output_path = os.path.join(OUTPUT_DIR, "2_1_pepper_avg_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, averaging_mask(peppered, filter_size=5))
def task2_4(): img = normalize_intensity(imread(CAMERAMAN)) img = img[30:95, [i for i in range(80, 160)]] # select subsection of image vel_x, vel_y = gradient(f=img) magn_img = gaussian_gradient_magnitude(img, 3) output_path = os.path.join(OUTPUT_DIR, "2_4_gradien_magnitude_" + os.path.split(CAMERAMAN)[-1]) imsave(output_path, magn_img) dim_x, dim_y = len(img[0]), len(img) x, y = range(dim_x), range(dim_y) x, y = meshgrid(x, y) plt.figure() imgplot = plt.imshow(img) imgplot.set_cmap('gray') plt.ylim(dim_y, 0) plt.quiver(x, y, vel_x, vel_y, pivot='middle') plt.show()
def task4_2(): matrix = random_matrix(4, 4, n=8) output_path = os.path.join(OUTPUT_DIR, 'original_matrix.png') imsave(output_path, matrix) histogram = create_histogram(matrix) normalized = normalize_histogram(histogram) cdf = create_cdf(normalized) image = transform(matrix, cdf) print(matrix) print(image) output_path = os.path.join(OUTPUT_DIR, 'normalized_matrix.png') imsave(output_path, image) pl.imshow(image, cmap=cm.Greys_r) pl.show() einstein = imread(EINSTEIN) ein_cdf = create_cdf(normalize_histogram(create_histogram(einstein))) imsave(os.path.join(OUTPUT_DIR, "cdf_" + os.path.split(EINSTEIN)[-1]), transform(einstein, ein_cdf))
skip_mean_acc_ice_1 = skip_mean_acc_ice_2 = 0 skip_mean_IU_ice_1 = skip_mean_IU_ice_2 = 0 print_and_write('Predicting on {:d} images'.format(n_frames), log_fname) print_and_write('Using {} as psi activation function'.format( model.psi_act_name)) print_diff = int(n_frames * 0.1) for img_id in range(start_id, end_id + 1): img_fname = src_files[img_id] img_fname_no_ext = os.path.splitext(img_fname)[0] src_img_fname = os.path.join(images_path, img_fname) src_img_orig = imread(src_img_fname) if src_img_orig is None: raise SystemError('Source image could not be read from: {}'.format( src_img_fname)) # print('src_img_orig.shape:', src_img_orig.shape) src_img = src_img_orig / np.amax(src_img_orig) src_img = np.reshape(src_img, (1, height, width, 3)).astype(np.float32) _start_t = time.time() phi_val = model.phi.eval(feed_dict={model.X: src_img}) _end_t = time.time() fps = 1.0 / float(_end_t - _start_t) ClassIndicator = phi_val.reshape((height, width, n_classes))
"""Delete objects""" del img del adj_mat del net return new_img if __name__ == '__main__': """Define the noisy image location""" in_fname = 'noisy.png' """Define the output path to save intermediate denoised images to""" out_fname = '.\\output\\' """Load the image""" img = np.array(imread(in_fname, 1)/255, dtype=int) """Determine the images depth""" depth = np.max(img)+1 """Define the sliding window size""" seg_size = 100 """ If the image is smaller that the sliding window, then just denoise the whole image """ if img.shape[0]<seg_size: new_img = denoise_image(img) imsave(out_fname + str(1) + '.png', new_img) else:
from numpy import linspace, pi, sin, cos from pylab import plot, subplot, cm, imshow, xlabel, ylabel, title, grid, \ axis, show, savefig, tight_layout # The following import *is* needed in PyLab. # The PyLab version of 'imread' does not read JPEGs. from scipy.misc.pilutil import imread x = linspace(0, 2*pi, 101) s = sin(x) c = cos(x) # 'flatten' creates a 2D array from a JPEG. img = imread('dc_metro.jpg', flatten=True) subplot(2,2,1) plot(x, s, 'b-', x, c, 'r+') axis('tight') subplot(2,2,2) plot(x, s) grid() xlabel('radians') ylabel('amplitude') title('sin(x)') axis('tight') subplot(2,2,3) imshow(img, extent=[-10, 10, -10, 10], cmap=cm.winter) tight_layout() show() savefig('plotting.png')
from scipy import ndimage # from scipy.misc import imread from scipy.misc.pilutil import imread from scipy.ndimage import (label, find_objects) import scipy.ndimage.measurements as meas # edge_horizont = ndimage.sobel(greyscale, 0) # edge_vertical = ndimage.sobel(greyscale, 1) # magnitude = np.hypot(edge_horizont, edge_vertical) # from scipy import ndimage img = imread('f.png') x, y = label(img) image_threshold = .5 label_array, n_features = ndimage.label(x > image_threshold) slices = meas.find_objects(label_array) print(slices) print(n_features) # Plot the resulting shapes import pylab as plt plt.subplot(121) plt.imshow(x) plt.subplot(122) plt.imshow(label_array) plt.show()
for row in basis: if count == 0: basis_vect = row count = count + 1 ortho_basis.append(basis_vect) else: temp_vect = row for vect in ortho_basis: temp_vect = temp_vect - ( (np.dot(row, vect) / np.dot(vect, vect)) * vect) ortho_basis.append(temp_vect) return ortho_basis except Exception as exc: raise exc if __name__ == '__main__': # 1. Load the hendrix_final.png image and extract the R, G and B channels. read_image = imread("hendrix_final.png", mode="RGB") # 1.1 Convert each channel image to double precision. read_image = skimage.img_as_float(read_image) # 1.2 Extract R, G and B channels r_chan = read_image[:, :, 0] orthogonal_basis = graham_schmidt(r_chan)
dtype=tf.float32, stddev=1e-1), name='weights') fc3b = tf.Variable(tf.constant(1.0, shape=[1000], dtype=tf.float32), trainable=True, name='biases') self.fc3l = tf.nn.bias_add(tf.matmul(self.fc2, fc3w), fc3b) self.parameters += [fc3w, fc3b] def load_weights(self, weight_file, sess): weights = np.load(weight_file) keys = sorted(weights.keys()) for i, k in enumerate(keys): print(i, k, np.shape(weights[k])) sess.run(self.parameters[i].assign(weights[k])) if __name__ == '__main__': sess = tf.Session() imgs = tf.placeholder(tf.float32, [None, 224, 224, 3]) vgg = vgg16(imgs, 'vgg16_weights.zip', sess) img1 = imread('dog1.bmp', mode='RGB') img1 = imresize(img1, (224, 224, 3)) prob = sess.run(vgg.probs, feed_dict={vgg.imgs: [img1]})[0] preds = (np.argsort(prob)[::-1])[0:5] for p in preds: print(class_names[p], prob[p])
""" from scipy.misc.pilutil import imread from matplotlib.pyplot import figure, subplot, imshow, title, show, gray, cm def smooth(img): avg_img =( img[1:-1 ,1:-1] # center + img[ :-2 ,1:-1] # top + img[2: ,1:-1] # bottom + img[1:-1 , :-2] # left + img[1:-1 ,2: ] # right ) / 5.0 return avg_img # 'flatten' creates a 2D array from a JPEG. img = imread('dc_metro.JPG', flatten=True) avg_img = smooth(img) figure() # Set colormap so that images are plotted in gray scale. gray() # Plot the original image first subplot(1,3,1) imshow(img) title('original') # Now the filtered image. subplot(1,3,2) imshow(avg_img) title('smoothed once')
def manual(img1, img2, k, x): rows1 = img1.shape[0] cols1 = img1.shape[1] channel1 = img1.shape[2] rows2 = img2.shape[0] cols2 = img2.shape[1] channel2 = img2.shape[2] image1 = img1.reshape((rows1*cols1), channel1) image2 = img2.reshape((rows2*cols2), channel2) #print(img1) pixel1 = img1[1, 2] pixel2 = img2[3, 4] pixel3 = img2[5, 6] newImage = np.concatenate((image1, image2), axis =0) pixels = [] pixels.append(pixel1) pixels.append(pixel2) pixels.append(pixel3) #print(np.array(pixels)) km = KMeans(n_clusters = k, init = np.array(pixels), n_init = 1) km.fit(newImage) clusters = np.array(km.cluster_centers_) labels = np.array(km.labels_) labels = labels.reshape(rows1*2, cols1) #cv2.imwrite("out.jpg", labels) #print(clusters) imsave("out.jpg", labels) '''im = imread("105c.jpg") im = convertColorSpace(im) rows0 = im.shape[0] cols0 = im.shape[1] channel0 = im.shape[2] image = im.reshape(rows0*cols0, channel0) new = km.predict(image) labels0 = np.array(new) labels0 = labels0.reshape(rows0, cols0) imsave("outer.jpg", labels0)''' #################################################### if x == 1: i = 1 imageList = [] imageDir = "filarioidea/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "filaria_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1 elif x == 2: i = 1 imageList = [] imageDir = "schistoma/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "schistoma_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1 elif x == 3: i = 1 imageList = [] imageDir = "plasmodium/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "plasmodium_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1
def main(): what = input("Random(1) or Manual(2)\n") if what == '1': k = 3 k1 = 2 #print("filaria") img1 = imread("filaria.jpg") img2 = imread("filaria4.jpg") #img1 = convertColorSpace(img1) #img2 = convertColorSpace(img2) #imsave("fudge.jpg", img1) #imsave("fudge1.jpg",img2) train(img1, img2, k, 1) #print("schistoma") img1 = imread("schistoma5.jpg") img2 = imread("schistoma6.jpg") img1 = convertColorSpace(img1) img2 = convertColorSpace(img2) train(img1, img2, k, 2) #print("plasmodium") img1 = imread("7c.jpg") img2 = imread("55c.jpg") img1 = convertColorSpace(img1) img2 = convertColorSpace(img2) train(img1, img2, k1, 3) elif what == '2': img1 = imread("filaria.jpg") img2 = imread("filaria4.jpg") img1 = convertColorSpace(img1) img2 = convertColorSpace(img2) manual(img1, img2, 3, 1) img1 = imread("schistoma5.jpg") img2 = imread("schistoma6.jpg") img1 = convertColorSpace(img1) img2 = convertColorSpace(img2) manual(img1, img2, 3, 2) img1 = imread("7c.jpg") img2 = imread("55c.jpg") img1 = convertColorSpace(img1) img2 = convertColorSpace(img2) manual(img1, img2, 2, 3) '''img1 = imread("filaria.jpg")
def create_input_files(dataset, karpathy_json_path, image_folder, captions_per_image, min_word_freq, output_folder, max_len=100): """ Creates input files for training, validation, and test data. :param dataset: name of dataset, one of 'coco', 'flickr8k', 'flickr30k' :param karpathy_json_path: path of Karpathy JSON file with splits and captions :param image_folder: folder with downloaded images :param captions_per_image: number of captions to sample per image :param min_word_freq: words occuring less frequently than this threshold are binned as <unk>s :param output_folder: folder to save files :param max_len: don't sample captions longer than this length """ assert dataset in {'coco', 'flickr8k', 'flickr30k'} # Read Karpathy JSON with open(karpathy_json_path, 'r') as j: data = json.load(j) # Read image paths and captions for each image train_image_paths = [] train_image_captions = [] val_image_paths = [] val_image_captions = [] test_image_paths = [] test_image_captions = [] word_freq = Counter() for img in data['images']: captions = [] for c in img['sentences']: # Update word frequency word_freq.update(c['tokens']) if len(c['tokens']) <= max_len: captions.append(c['tokens']) if len(captions) == 0: continue path = os.path.join(image_folder, img['filepath'], img['filename']) if dataset == 'coco' else os.path.join( image_folder, img['filename']) if img['split'] in {'train', 'restval'}: train_image_paths.append(path) train_image_captions.append(captions) elif img['split'] in {'val'}: val_image_paths.append(path) val_image_captions.append(captions) elif img['split'] in {'test'}: test_image_paths.append(path) test_image_captions.append(captions) # Sanity check assert len(train_image_paths) == len(train_image_captions) assert len(val_image_paths) == len(val_image_captions) assert len(test_image_paths) == len(test_image_captions) # Create word map words = [w for w in word_freq.keys() if word_freq[w] > min_word_freq] word_map = {k: v + 1 for v, k in enumerate(words)} word_map['<unk>'] = len(word_map) + 1 word_map['<start>'] = len(word_map) + 1 word_map['<end>'] = len(word_map) + 1 word_map['<pad>'] = 0 # Create a base/root name for all output files base_filename = dataset + '_' + str(captions_per_image) + '_cap_per_img_' + str(min_word_freq) + '_min_word_freq' # Save word map to a JSON with open(os.path.join(output_folder, 'WORDMAP_' + base_filename + '.json'), 'w') as j: json.dump(word_map, j) # Sample captions for each image, save images to HDF5 file, and captions and their lengths to JSON files seed(123) for impaths, imcaps, split in [(train_image_paths, train_image_captions, 'TRAIN'), (val_image_paths, val_image_captions, 'VAL'), (test_image_paths, test_image_captions, 'TEST')]: with h5py.File(os.path.join(output_folder, split + '_IMAGES_' + base_filename + '.hdf5'), 'a') as h: # Make a note of the number of captions we are sampling per image h.attrs['captions_per_image'] = captions_per_image # Create dataset inside HDF5 file to store images images = h.create_dataset('images', (len(impaths), 3, 256, 256), dtype='uint8') print("\nReading %s images and captions, storing to file...\n" % split) enc_captions = [] caplens = [] for i, path in enumerate(tqdm(impaths)): # Sample captions if len(imcaps[i]) < captions_per_image: captions = imcaps[i] + [choice(imcaps[i]) for _ in range(captions_per_image - len(imcaps[i]))] else: captions = sample(imcaps[i], k=captions_per_image) # Sanity check assert len(captions) == captions_per_image # Read images img = imread(impaths[i]) if len(img.shape) == 2: img = img[:, :, np.newaxis] img = np.concatenate([img, img, img], axis=2) img = imresize(img, (256, 256)) img = img.transpose(2, 0, 1) assert img.shape == (3, 256, 256) assert np.max(img) <= 255 # Save image to HDF5 file images[i] = img for j, c in enumerate(captions): # Encode captions enc_c = [word_map['<start>']] + [word_map.get(word, word_map['<unk>']) for word in c] + [ word_map['<end>']] + [word_map['<pad>']] * (max_len - len(c)) # Find caption lengths c_len = len(c) + 2 enc_captions.append(enc_c) caplens.append(c_len) os.remove(impaths[i]) # Sanity check assert images.shape[0] * captions_per_image == len(enc_captions) == len(caplens) # Save encoded captions and their lengths to JSON files with open(os.path.join(output_folder, split + '_CAPTIONS_' + base_filename + '.json'), 'w') as j: json.dump(enc_captions, j) with open(os.path.join(output_folder, split + '_CAPLENS_' + base_filename + '.json'), 'w') as j: json.dump(caplens, j)
def _imread(image_name): return imread(image_name)
def img2array(afilename): img = imread(afilename,0) # return np.array(img) return img
#!/usr/bin/env python from os import listdir from scipy.misc.pilutil import imread from sklearn import svm from sklearn.externals import joblib from sklearn.datasets.base import Bunch bot = svm.SVC() data_dir = "data/" samples=[(target, imread(data_dir + target + "/" + filename).flatten()) for target in listdir(data_dir) # beware .DS_store for filename in listdir(data_dir+target)] inputs,images = zip(*samples) # dataset = Bunch(data=images,targets=inputs) bot.fit(images,inputs) joblib.dump(bot,"bot/bot.pkl")
print " - resize %0.3f sec (%s)" % (end, name) # scipy if HAS_NUMPY: tiff = pil_open(TIFF) tiff.load() start = time() for i in xrange(RW_COUNT): arr = asarray(tiff) bytescale(arr, 64, 192) end = time() - start print " - tiff numpy.asarray() with bytescale() %0.3f sec" % end start = time() for i in xrange(RW_COUNT): arr = imread(TIFF) bytescale(arr, 64, 192) end = time() - start print " - tiff scipy imread() with bytescale() %0.3f sec" % end # ------------------------------------------------------------------- # pgmagick load if HAS_PGMAGICK: hdr = ("pgmagick %s (%s %s) (with standard libjpeg)" % (pgmagick.__version__, pgmagick.gminfo.library, pgmagick.gminfo.version)) print "\n%s\n%s" % (hdr, "-" * len(hdr)) start = time() for i in xrange(RW_COUNT): PGMagickImage(IMG) end = time() - start
import skimage.filters as fs import numpy as np from skimage import feature from scipy.misc import pilutil as pu from scipy.misc.pilutil import Image from skimage import data, color, exposure, img_as_float, io from skimage.feature import hog #directory navigation i.e. path to image path = '/home/austen/PycharmProjects/Polar Nephelometer/Data/05-10-2017/plots/Sum5Images.BMP' #Image.open reads the BMP as an image format im = Image.open(path).convert('L') #imread reads the image as a Matrix, the other a 2D array imMat = pu.imread(path) imArray = mi.fromimage(im) #Sobel filtering the image, looks decent for edge detection sobel_filter_im = fs.sobel(im) sobel_filter_imh = fs.sobel_h(im) sobel_filter_imv = fs.sobel_v(im) sobel_filter_im = mi.toimage(sobel_filter_im) sobel_filter_imh = mi.toimage(sobel_filter_imh) sobel_filter_imv = mi.toimage(sobel_filter_imv) #sobel_filter_im.show() ''' #scipy sobel filter sx = filters.sobel(im, axis=0, mode='constant') sy = filters.sobel(im, axis=1, mode='constant') sob = np.hypot(sx, sy)
def train(img1, img2, k, x): rows1 = img1.shape[0] cols1 = img1.shape[1] channel1 = img1.shape[2] rows2 = img2.shape[0] cols2 = img2.shape[1] channel2 = img2.shape[2] image1 = img1.reshape((rows1*cols1), channel1) image2 = img2.reshape((rows2*cols2), channel2) newImage = np.concatenate((image1, image2), axis =0) km = KMeans(n_clusters = k) km.fit(newImage) clusters = np.array(km.cluster_centers_) labels = np.array(km.labels_) labels = labels.reshape(rows1*2, cols1) #cv2.imwrite("out.jpg", labels) #labels.append(img1.shape[2]) imsave("out.jpg", labels) #imsave("D:/Owl/CS180/MP2/output/out.jpg", labels) '''im = imread("filaria.jpg") im = convertColorSpace(im) rows0 = im.shape[0] cols0 = im.shape[1] channel0 = im.shape[2] image = im.reshape(rows0*cols0, channel0) new = km.predict(image) labels0 = np.array(new) labels0 = labels0.reshape(rows0, cols0) #labels0 = cv2.cvtColor(labels0, cv2.COLOR_HSV2BGR) imsave("outerer.jpg", labels0)''' #labels0 = cv2.cvtColor(im, cv2.COLOR_HSV2BGR) ############################################## if x == 1: i = 1 imageList = [] imageDir = "filarioidea/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "filaria_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1 elif x == 2: i = 1 imageList = [] imageDir = "schistoma/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "schistoma_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1 elif x == 3: i = 1 imageList = [] imageDir = "plasmodium/" #imageDir = "plasmodium/" #imageDir = "schistoma/" imageExte = ".jpg" for filename in os.listdir(imageDir): extension = os.path.splitext(filename)[1] if extension.lower() != imageExte: continue imageList.append(os.path.join(imageDir, filename)) for imagePath in imageList: #image = cv2.imread(imagePath) #cluster(image, centroids, 3, i) im = imread(imagePath) im = convertColorSpace(im) rows1 = im.shape[0] cols1 = im.shape[1] channel1 = im.shape[2] image = im.reshape(rows1*cols1, channel1) new = km.predict(image) labels1 = np.array(new) labels1 = labels1.reshape(rows1, cols1) output = "plasmodium_clustered{}.jpg".format(i) imsave(output, labels1) i = i + 1
img = np.concatenate((img, vect_pad), axis=1) return img except Exception as exc: print("Exception %s in %s" % (exc, func_tag)) raise exc if __name__ == '__main__': total_patches = 1000 dimension_index = 0 size_patch = 16 # 1. Read the image read_image = imread("clockwork-angels.jpg", mode="RGB") # 2. Pick the first dimension of the image chosen_dimension = read_image[:, :, dimension_index] # 3. Creating 1000 random 16x16 patches rand_pat = get_random_patches(chosen_dimension, total_patches, size_patch) # 4.1 Reshaping the patches created above reshape_patches = get_reshaped_patch(rand_pat, size_patch, total_patches) # 4.2 Computing teh correlation matrix corr_mat = compute_correlation_matrix(reshape_patches, 256) # 5.1 Computing all eigenvectors of above matrix eig_val, eig_vec = np.linalg.eig(corr_mat)
for k, ln2 in enumerate(ep_lines): a, b, c = ln2 x, y, _ = points2[k] error.append([abs(a * x + b * y + 1.0 * c)]) return np.array(error).mean() if __name__ == '__main__': for im_set in ['data/set1', 'data/set2']: print('-' * 80) print("Set:", im_set) print('-' * 80) # Read in the data im1 = imread(im_set + '/image1.jpg') im2 = imread(im_set + '/image2.jpg') points1 = get_data_from_txt_file(im_set + '/pt_2D_1.txt') points2 = get_data_from_txt_file(im_set + '/pt_2D_2.txt') assert (points1.shape == points2.shape) # Running the linear least squares eight point algorithm F_lls = lls_eight_point_alg(points1, points2) print("Fundamental Matrix from LLS 8-point algorithm:\n", F_lls) print("Distance to lines in image 1 for LLS:", \ compute_distance_to_epipolar_lines(points1, points2, F_lls)) print("Distance to lines in image 2 for LLS:", \ compute_distance_to_epipolar_lines(points2, points1, F_lls.T)) # Running the normalized eight point algorithm F_normalized = normalized_eight_point_alg(points1, points2)
import medcoupling as MC import MEDLoader as ML # # =============================================================== # We first get data from the test image to render as a field # =============================================================== # import scipy, numpy # The data field array may be created from the lena image #image = scipy.lena() # We could either read a real image using the PIL python package. from scipy.misc import pilutil CURDIR = os.path.dirname(__file__) image = pilutil.imread(os.path.join(CURDIR, "images", "avatar.png"), True) #from PIL import Image #im=Image.open("images/irm.png") #im=Image.open("images/lena.png") #image=pilutil.fromimage(im,True) #image=numpy.asarray(im) # print(image) dim = len(image.shape) print("Image space dimension = %d" % dim) sizeX = image.shape[1] sizeY = image.shape[0] # The sizes defined the number of pixel in a direction, then the # number of cells to create in the mesh in that direction.
def read_image(name): return imread(name, True)
from numpy import array, float32, int8, int32, max, min from scipy.stats import threshold from scipy.cluster.vq import vq, kmeans2, whiten from scipy.ndimage.measurements import watershed_ift from scipy.misc.pilutil import imread, imsave from matplotlib.pyplot import imshow import color img = imread("blue.jpg") markers = imread("bluem2.jpg") markers = int32(markers[:, :, 1]) markers = threshold(markers, 100, None, 1) # black to 1 print max(markers) print min(markers) markers = threshold(markers, None, 200, -1) # white to -1 print max(markers) print min(markers) markers = threshold(markers, None, 2, 0) # gray to 0 markers = int8(markers) mask = watershed_ift(img[:, :, 1], markers) print mask mask = mask + 1 print mask print max(mask) mask = threshold(mask, None, 1, 1) print max(mask) mask = 255 * mask imsave("mask_watershed.jpg", mask)
def apply_nnf(nnf , original): shifted = zeros(original.shape) for y in range(original.shape[1]): for x in range(original.shape[0]): shift_x = nnf[x , y, 0] shift_y = nnf[x , y , 1] shifted[x , y] = original[shift_x , shift_y] return shifted #im_one = imread('r.jpg' , flatten=1) im_two = around(imread('camel.jpg' , flatten=1)) print im_two.shape print im_two #im_two[125:200 , 325:425] = random_integers(0 , 255 , (75 , 100)) #im_two[125:200 , 325:425] = im_two.mean() im_one = im_two[90:210 , 290:462].copy() #im_two[125:200 , 325:425] = random_integers(0 , 255 , (75 , 100)) im_one_weights = ones(im_one.shape) im_two_weights = zeros(im_two.shape) im_one_weights[im_one < 128] = 0 im_two_weights[im_two < 140] = 128
# x = plot_data_ev[:,0] # y = plot_data_ev[:,1] # s = 1.5 # bins = 800 #np.histogram2d()将两列数值转为矩阵 heatmap, xedges, yedges = np.histogram2d(x, y, bins = bins) #高斯锐化模糊对象 heatmap = gaussian_filter(heatmap, sigma = s) extent = [xedges[0], xedges[-1], yedges[0], yedges[-1]] return heatmap.T, extent #读取森林地图底图 #Normalize归一化 #np.clip(x,a,b)将x中小于a的值设为a,大于b的值设为b #cm.bwr 蓝白红 bg = imread('erangel.jpg') hmap, extent = heatmap(plot_data_ev[:,0], plot_data_ev[:,1], 1.5, bins =800) alphas = np.clip(Normalize(0, hmap.max()/100, clip=True)(hmap)*1.5,0.0,1.) colors = Normalize(hmap.max()/100, hmap.max()/20, clip=True)(hmap) colors = cm.bwr(colors) colors[..., -1] = alphas hmap2, extent2 = heatmap(plot_data_ek[:,0],plot_data_ek[:,1],1.5, bins = 800) alphas2 = np.clip(Normalize(0, hmap2.max()/100, clip = True)(hmap2)*1.5, 0.0, 1.) colors2 = Normalize(hmap2.max()/100, hmap2.max()/20, clip=True)(hmap2) colors2 = cm.RdBu(colors2) colors2[...,-1] = alphas2 #'森林死亡率图' fig, ax = plt.subplots(figsize = (24,24)) ax.set_xlim(0, 4096);ax.set_ylim(0, 4096)
def flatten(filename): img = imread(filename) return img.flatten()
4. The `subplot()` function returns an axes object, which can be assigned to the `sharex` and `sharey` keyword arguments of another subplot() function call. E.g.:: ax1 = subplot(2,2,1) ... subplot(2,2,2, sharex=ax1, sharey=ax1) Make this modification to your script, and explore the consequences. Hint: try panning and zooming in the subplots. See :ref:`plotting-solution`. """ # The following imports are *not* needed in PyLab, but are needed in this file. from numpy import linspace, pi, sin, cos from pylab import plot, subplot, cm, imshow, xlabel, ylabel, title, grid, axis, show, savefig # The following import *is* needed in PyLab. # The PyLab version of 'imread' does not read JPEGs. from scipy.misc.pilutil import imread x = linspace(0, 2 * pi, 101) s = sin(x) c = cos(x) # 'flatten' creates a 2D array from a JPEG. img = imread("dc_metro.JPG", flatten=True)
def __init__(self,fileName): self.mask = imread(fileName) > 0 self.notMask = logical_not(self.mask) self.positives = count_nonzero(self.mask)*1.0 self.negatives = (self.mask.size - self.positives)*1.0
def loadTsign(filePath): tSign = imread(filePath) tSign = cv2.cvtColor(tSign, cv2.COLOR_RGB2GRAY) # tSign = deskew(tSign) tSign = cv2.resize(tSign, (128, 128)) return tSign
def checkClassification(self,binary): fp = count_nonzero(logical_and(self.notMask, binary)) tp = count_nonzero(logical_and(self.mask,binary)) return fp,tp def getBlackWhiteFromBinary(img): return dstack((img,img,img)) if __name__ == '__main__': seterr(all='warn') skindata, nonskindata = loadmat('data/skin.mat')['sdata'].reshape((-1, 3)).astype(float128), loadmat('data/nonskin.mat')['ndata'].reshape((-1, 3)).astype(float128) iters = 10 show = False usekmeans = False gmmskin, gmmnonskin = gmmEM(skindata, 2, iters,show,usekmeans), gmmEM(nonskindata, 2, iters,show,usekmeans) img = imread('data/image.png').astype(float128) / 255.0 imshape = img.shape img = img.reshape((-1, 3)) skinp, nonskinp = gmmskin.getP(img), gmmnonskin.getP(img) res = skinp > nonskinp res = res.reshape((imshape[0],imshape[1])) res = logical_not(res) gt = GroundTruth('data/mask.png') fp, tp = gt.checkClassification(res) print "false positive ratio: ", fp*1.0/gt.negatives print "true positive ratio: ", tp*1.0/gt.positives res = getBlackWhiteFromBinary(res) pylab.figure() pylab.imshow(res)
for a in act: # print act name = a.split()[1].lower() i = 0 for line in open("facescrub_actresses.txt"): if a in line: filename = name + str(i) + '.' + line.split()[4].split('.')[-1] face_dim = line.split("\t")[4].split(',') face_dim = [int(j) for j in face_dim] # print(face_dim) #A version without timeout (uncomment in case you need to #unsupress exceptions, which timeout() does) #testfile.retrieve(line.split()[4], "uncropped/"+filename) #timeout is used to stop downloading images which take too long to download timeout(testfile.retrieve, (line.split()[4], "uncropped/" + filename), {}, 30) if not os.path.isfile("uncropped/" + filename): continue try: imarray = imread("uncropped/" + filename) except: continue cropped = imarray[face_dim[1]:face_dim[3], face_dim[0]:face_dim[2]] resized = imresize(cropped, (32, 32)) if len(resized.shape) == 3: grayscale = rgb2gray(resized) imsave("cropped/" + filename, grayscale) print filename i += 1
def load(self): array = imread(self.url) self.array = (exposure.rescale_intensity(array * 1.0) * (len(np.unique(array)) - 1)).astype(int) # rescale to contain integer grayscale id's. return self.array
tick = 20 # milliseconds velocity = 1 ang_velocity = 10 # robotRadius = 0.7 # sensorRadius = 6 # swarmSize = 90 # shapeWidth = 7 # tick = 20 # milliseconds # velocity = 1 # ang_velocity = 5 file_path = "shapes/tumor100.png" bitmap = BitMap(file_path) origin = bitmap.origin datafile = open(file_path) img = imread(datafile, mode='L') img[np.nonzero(img - 255)] = 0 fieldSizeX1 = 0 fieldSizeX2 = 100 + fieldSizeX1 fieldSizeY1 = 0 fieldSizeY2 = 100 + fieldSizeY1 #shape to assemble shapeX = np.array([0, 20, 20, 10, 10, 0, 0]) shapeY = np.array([0, 0, 10, 10, 20, 20, 0]) shapeOffsetX = 0 shapeOffsetY = 0 scaleX = 1 scaleY = 1
def open_image(self): data = imread(self.filenames.selected) for f in self.filters: data = f.process(data) self.data = data
Plot the image, the smoothed image, and the difference between the two. Bonus ~~~~~ Re-filter the image by passing the result image through the filter again. Do this 50 times and plot the resulting image. """ from scipy.misc.pilutil import imread from matplotlib.pyplot import figure, subplot, imshow, title, show, gray # 'flatten' creates a 2D array from a JPEG. img = imread('dc_metro.JPG', flatten=True) avg_img = ( img[1:-1, 1:-1] # center + img[:-2, 1:-1] # top + img[2:, 1:-1] # bottom + img[1:-1, :-2] # left + img[1:-1, 2:] # right ) / 5.0 figure() # Set colormap so that images are plotted in gray scale. gray() # Plot the original image first subplot(1, 3, 1) imshow(img)
H=theStrongConnect[theUnassigned] temp2=time.time() for h in H: theIndex=combo.index((theLambda[h],h)) del combo[theIndex] theLambda[h]+=1 combo.insert(theIndex,(theLambda[h],h)) #hFiltTime+=time.time()-temp2 #kFiltTime+=time.time()-temp C=where(T==1)[0] print '%f seconds'%(time.time()-curr) return C #final assignment of pixels to most appropriate segment def assignPixels(self): return if __name__ == "__main__": #anImage = pilutil.imread('testImage.png',flatten=True) anImage = pilutil.imread('bob00177.jpg',flatten=True) theSWA=SWA() theSWA.SetImage(anImage) C=theSWA.imageVCycle() theSWA.assignPixels(C) print 'finished setup'
if response >= 0: img3[int(y), int(x), 0] = 255 img3[int(y), int(x), 1] = 0 img3[int(y), int(x), 2] = 0 else: img3[int(y), int(x), 0] = 0 img3[int(y), int(x), 1] = 0 img3[int(y), int(x), 2] = 255 imsave('/home/cplab/workspace/imageex/src/imageex/static/STARRRRR.png', img3) return [] #img = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/EPZZtChQXE.JPG') #mask = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/segmentation/AxHBuxBWZE.png') img = imread( '/home/cplab/workspace/imageex/src/imageex/static/uploads/IwmzjtKPUf.jpg') mask = imread( '/home/cplab/workspace/imageex/src/imageex/static/uploads/segmentation/CidVVYLJfe.png' ) hsv = rgb2hsv(img) greyscaleImg = rgb_2_greyscale(img) features = shapeAnalysis(mask) features += colorAnalysis(hsv, mask) #features += featurePoints(greyscaleImg, mask) print "features : ", features nbFeatures = len(features) n, m = 100, 2
def main(params): imgs = json.load(open(params['input_json'], 'r')) seed(123) # make reproducible shuffle(imgs) # shuffle the order # tokenization and preprocessing prepro_captions(imgs) # create the vocab vocab = build_vocab(imgs, params) itow = {i + 1: w for i, w in enumerate(vocab) } # a 1-indexed vocab translation table wtoi = {w: i + 1 for i, w in enumerate(vocab)} # inverse table # assign the splits assign_splits(imgs, params) # encode captions in large arrays, ready to ship to hdf5 file L, label_start_ix, label_end_ix, label_length = encode_captions( imgs, params, wtoi) # create output h5 file N = len(imgs) f = h5py.File(params['output_h5'], "w") f.create_dataset("labels", dtype='uint32', data=L) f.create_dataset("label_start_ix", dtype='uint32', data=label_start_ix) f.create_dataset("label_end_ix", dtype='uint32', data=label_end_ix) f.create_dataset("label_length", dtype='uint32', data=label_length) dset = f.create_dataset("images", (N, 3, 256, 256), dtype='uint8') # space for resized images for i, img in enumerate(imgs): # load the image I = imread(os.path.join(params['images_root'], img['file_path'])) try: Ir = imresize(I, (256, 256)) except: print 'failed resizing image %s - see http://git.io/vBIE0' % ( img['file_path'], ) raise # handle grayscale input images if len(Ir.shape) == 2: Ir = Ir[:, :, np.newaxis] Ir = np.concatenate((Ir, Ir, Ir), axis=2) # and swap order of axes from (256,256,3) to (3,256,256) Ir = Ir.transpose(2, 0, 1) # write to h5 dset[i] = Ir if i % 1000 == 0: print 'processing %d/%d (%.2f%% done)' % (i, N, i * 100.0 / N) f.close() print 'wrote ', params['output_h5'] # create output json file out = {} out['ix_to_word'] = itow # encode the (1-indexed) vocab out['images'] = [] for i, img in enumerate(imgs): jimg = {} jimg['split'] = img['split'] if 'file_path' in img: jimg['file_path'] = img['file_path'] # copy it over, might need if 'id' in img: jimg['id'] = img[ 'id'] # copy over & mantain an id, if present (e.g. coco ids, useful) out['images'].append(jimg) json.dump(out, open(params['output_json'], 'w')) print 'wrote ', params['output_json']
def generator_test_img(list_dir): output_training_img = [ imresize(imread(i, mode='L'), (128, 128)) for i in list_dir ] output_training_img = np.array(output_training_img) / 255.0 return output_training_img
# path for image C:\Users\haame\DSND_Term1\projects/python_bgn # Python script using Scipy # for image manipulation , # from scipy.misc import from scipy.misc.pilutil import imread, imsave, imresize # from scipy.misc.pilutil import Image as img # import Image # Read a JPEG image into a numpy array img = imread('C:/Users/haame/DSND_Term1/projects/python_bgn/drgnfly.jpg' ) # path of the image print(img.dtype, img.shape) # Tinting the image img_tint = img * [1, 0.45, 0.3] # Saving the tinted image imsave('C:/Users/haame/DSND_Term1/projects/python_bgn/drgnfly_2.jpg', img_tint) # Resizing the tinted image to be 300 x 300 pixels img_tint_resize = imresize(img_tint, (300, 300)) # Saving the resized tinted image imsave( 'C:/Users/haame/DSND_Term1/projects/python_bgn/drgnfly_tinted_resized.jpg', img_tint_resize)
from skimage import feature from scipy.misc import pilutil as pu from scipy.misc.pilutil import Image from skimage import exposure from scipy.optimize import curve_fit from skimage import color, io, img_as_float #directory navigation i.e. path to image path_windows = 'C:/Users/sm2/Documents/Github Repository Clone/Polar-Nephelometer/Data/06-19-2017/Image30s50mW.BMP' path_linux = '/home/austen/PycharmProjects/TSI-3563-INeph/Data/06-19-2017/Image30s50mW.BMP' #Image.open reads the BMP as an image format im = Image.open(path_windows) #imread reads the image as a Matrix, the other a 2D array imMat = pu.imread(path_windows) imArray = mi.fromimage(im) # Otsu method for thresholding automatically finds the value that maximizes the variance between the background and foreground # using skimages module we will conduct otsu thresholding # I have included a variable to tune up or down the thresholding as I please val_variable = -40 val = fs.threshold_otsu(imArray) + val_variable hist, bins_center = exposure.histogram(imArray) otsu_imArray = imArray > val otsu_im = mi.toimage(otsu_imArray) # Create figure showing otsu thresholding based upon raw image histogram f, ax = plt.subplots(1, 3) ax[0].imshow(imArray, cmap='gray', interpolation='nearest') ax[0].set_title('Raw Image')
from numpy import linspace, pi, sin, cos from pylab import plot, subplot, cm, imshow, xlabel, ylabel, \ title, grid, axis, show, savefig, gcf, figure, close, tight_layout from scipy.misc.pilutil import imread x = linspace(0, 2 * pi, 101) s = sin(x) c = cos(x) img = imread('dc_metro.JPG', flatten=True) # flatten creates a 2-D array from a JPEG close('all') # start by create a 2-by-2 plot grid and plot the 1st one subplot(2, 2, 1) plot(x, s, 'b-', x, c, 'r*') axis('tight') # move on to the 2nd plot subplot(2, 2, 2) plot(x, s) grid() xlabel('this is x') ylabel('this is s') title(' x vs s') axis('tight')
def load_tiny_imagenet(path, dtype=np.float32, subtract_mean=True): """ Load TinyImageNet. Each of TinyImageNet-100-A, TinyImageNet-100-B, and TinyImageNet-200 have the same directory structure, so this can be used to load any of them. Inputs: - path: String giving path to the directory to load. - dtype: numpy datatype used to load the data. - subtract_mean: Whether to subtract the mean training image. Returns: A dictionary with the following entries: - class_names: A list where class_names[i] is a list of strings giving the WordNet names for class i in the loaded dataset. - X_train: (N_tr, 3, 64, 64) array of training images - y_train: (N_tr,) array of training labels - X_val: (N_val, 3, 64, 64) array of validation images - y_val: (N_val,) array of validation labels - X_test: (N_test, 3, 64, 64) array of testing images. - y_test: (N_test,) array of test labels; if test labels are not available (such as in student code) then y_test will be None. - mean_image: (3, 64, 64) array giving mean training image """ # First load wnids with open(os.path.join(path, 'wnids.txt'), 'r') as f: wnids = [x.strip() for x in f] # Map wnids to integer labels wnid_to_label = {wnid: i for i, wnid in enumerate(wnids)} # Use words.txt to get names for each class with open(os.path.join(path, 'words.txt'), 'r') as f: wnid_to_words = dict(line.split('\t') for line in f) for wnid, words in wnid_to_words.items(): wnid_to_words[wnid] = [w.strip() for w in words.split(',')] class_names = [wnid_to_words[wnid] for wnid in wnids] # Next load training data. X_train = [] y_train = [] for i, wnid in enumerate(wnids): if (i + 1) % 20 == 0: print('loading training data for synset %d / %d' % (i + 1, len(wnids))) # To figure out the filenames we need to open the boxes file boxes_file = os.path.join(path, 'train', wnid, '%s_boxes.txt' % wnid) with open(boxes_file, 'r') as f: filenames = [x.split('\t')[0] for x in f] num_images = len(filenames) X_train_block = np.zeros((num_images, 3, 64, 64), dtype=dtype) y_train_block = wnid_to_label[wnid] * \ np.ones(num_images, dtype=np.int64) for j, img_file in enumerate(filenames): img_file = os.path.join(path, 'train', wnid, 'images', img_file) img = imread(img_file) if img.ndim == 2: ## grayscale file img.shape = (64, 64, 1) X_train_block[j] = img.transpose(2, 0, 1) X_train.append(X_train_block) y_train.append(y_train_block) # We need to concatenate all training data X_train = np.concatenate(X_train, axis=0) y_train = np.concatenate(y_train, axis=0) # Next load validation data with open(os.path.join(path, 'val', 'val_annotations.txt'), 'r') as f: img_files = [] val_wnids = [] for line in f: img_file, wnid = line.split('\t')[:2] img_files.append(img_file) val_wnids.append(wnid) num_val = len(img_files) y_val = np.array([wnid_to_label[wnid] for wnid in val_wnids]) X_val = np.zeros((num_val, 3, 64, 64), dtype=dtype) for i, img_file in enumerate(img_files): img_file = os.path.join(path, 'val', 'images', img_file) img = imread(img_file) if img.ndim == 2: img.shape = (64, 64, 1) X_val[i] = img.transpose(2, 0, 1) # Next load test images # Students won't have test labels, so we need to iterate over files in the # images directory. img_files = os.listdir(os.path.join(path, 'test', 'images')) X_test = np.zeros((len(img_files), 3, 64, 64), dtype=dtype) for i, img_file in enumerate(img_files): img_file = os.path.join(path, 'test', 'images', img_file) img = imread(img_file) if img.ndim == 2: img.shape = (64, 64, 1) X_test[i] = img.transpose(2, 0, 1) y_test = None y_test_file = os.path.join(path, 'test', 'test_annotations.txt') if os.path.isfile(y_test_file): with open(y_test_file, 'r') as f: img_file_to_wnid = {} for line in f: line = line.split('\t') img_file_to_wnid[line[0]] = line[1] y_test = [wnid_to_label[img_file_to_wnid[img_file]] for img_file in img_files] y_test = np.array(y_test) mean_image = X_train.mean(axis=0) if subtract_mean: X_train -= mean_image[None] X_val -= mean_image[None] X_test -= mean_image[None] return { 'class_names': class_names, 'X_train': X_train, 'y_train': y_train, 'X_val': X_val, 'y_val': y_val, 'X_test': X_test, 'y_test': y_test, 'class_names': class_names, 'mean_image': mean_image, }
img3 = np.array(img) for ((x, y), size, response) in star_keypoints: if response >= 0: img3[int(y),int(x), 0] = 255 img3[int(y),int(x), 1] = 0 img3[int(y),int(x), 2] = 0 else: img3[int(y),int(x), 0] = 0 img3[int(y),int(x), 1] = 0 img3[int(y),int(x), 2] = 255 imsave('/home/cplab/workspace/imageex/src/imageex/static/STARRRRR.png', img3) return [] #img = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/EPZZtChQXE.JPG') #mask = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/segmentation/AxHBuxBWZE.png') img = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/IwmzjtKPUf.jpg') mask = imread('/home/cplab/workspace/imageex/src/imageex/static/uploads/segmentation/CidVVYLJfe.png') hsv = rgb2hsv(img) greyscaleImg = rgb_2_greyscale(img) features = shapeAnalysis(mask) features += colorAnalysis(hsv, mask) #features += featurePoints(greyscaleImg, mask) print "features : ", features nbFeatures = len(features) n, m = 100, 2 # generate random sample, two components np.random.seed(0)
print " - resize %0.3f sec (%s)" % (end, name) # scipy if HAS_NUMPY: tiff = pil_open(TIFF) tiff.load() start = time() for i in xrange(RW_COUNT): arr = asarray(tiff) bytescale(arr, 64, 192) end = time() - start print " - tiff numpy.asarray() with bytescale() %0.3f sec" % end start = time() for i in xrange(RW_COUNT): arr = imread(TIFF) bytescale(arr, 64, 192) end = time() - start print " - tiff scipy imread() with bytescale() %0.3f sec" % end # ------------------------------------------------------------------- # pgmagick load if HAS_PGMAGICK: hdr = ("pgmagick %s (%s %s) (with standard libjpeg)" % (pgmagick.__version__, pgmagick.gminfo.library, pgmagick.gminfo.version)) print "\n%s\n%s" % (hdr, "-" * len(hdr)) start = time() for i in xrange(RW_COUNT): PGMagickImage(IMG)