def change_zoom(self, level, **kwargs): # convert pil image to np image pix = np.array(self.img.getdata()).reshape(self.img.size[0], self.img.size[1], 3) # get the height and width of image and then separate rgb of image to do each channel h, w = pix.shape[:2] zoom_tuple = (level, ) * 2 + (1, ) * (pix.ndim - 2) # Bounding box of the zoomed-in region within the input array zh = int(np.round(h / level)) zw = int(np.round(w / level)) top = (h - zh) // 2 left = (w - zw) // 2 out = zoom(pix[top:top + zh, left:left + zw], zoom_tuple, **kwargs) # `out` might still be slightly larger than `img` due to rounding, so # trim off any extra pixels at the edges trim_top = ((out.shape[0] - h) // 2) trim_left = ((out.shape[1] - w) // 2) out = out[trim_top:trim_top + h, trim_left:trim_left + w] # convert np image to pil image self.img = im.fromarray(np.uint8(cm.gist_earth(pix) * 255))
def combine_piezoscans_1D(folder, folder_array, time_array, threshold=None, xlimit=None): #matplotlib.rc ('xtick', labelsize=20) #matplotlib.rc ('ytick', labelsize=20) colori = cm.gist_earth(np.linspace(0, 0.75, len(folder_array))) f = plt.figure(figsize=(8, 40)) ax = f.add_subplot(1, 1, 1) i = 0 for k in folder_array: #print k V, Y = load_data(folder=folder, timestamp=k, scan_type='piezo') if threshold: ind = np.where(Y < threshold) Y[ind] = 0 ax.plot(V[:], 0.02 * Y[:] + (1 / 10.) * time_array[i], '.', color=colori[i]) ax.plot(V[:], 0.02 * Y[:] + (1 / 10.) * time_array[i], color=colori[i]) i = i + 1 ax.set_xlabel('piezo voltage [V]', fontsize=20) ax.set_ylabel('time [min]', fontsize=20) if xlimit: ax.set_xlim(xlimit) #f.savefig ('D:/measuring/low_temp_cavity.png', dpi=300) plt.show()
def sketch(img_arr): IM = Image.fromarray(np.uint8(cm.gist_earth(img_arr) * 255)) w, h = IM.size IM = IM.convert("L") IM = ImageOps.autocontrast(IM, 10) lines = [] if draw_contours: lines += getcontours( IM.resize((int(resolution / contour_simplify), int(resolution / contour_simplify * h / w))), contour_simplify) if draw_hatch: lines += hatch( IM.resize((int(resolution / hatch_size), int(resolution / hatch_size * h / w))), hatch_size) lines = sortlines(lines) if show_bitmap: disp = Image.new("RGB", (resolution, resolution * h / w), (255, 255, 255)) draw = ImageDraw.Draw(disp) for l in lines: draw.line(l, (0, 0, 0), 5) disp.show() f = open(export_path, 'w') f.write(makesvg(lines)) f.close() print(len(lines), "strokes.") print("done.") return lines
def infere_Class_Type(CallBack): if(not ringBuffer.is_full): return mel_spec_power = librosa.feature.melspectrogram(np.array(ringBuffer), sr=SpectrumVariables['SAMPLE_RATE'], n_fft=SpectrumVariables['N_FFT'], hop_length=SpectrumVariables['HOP_LENGTH'], n_mels=SpectrumVariables['N_MELS'], power=SpectrumVariables['POWER'], fmin=SpectrumVariables['FMIN'], fmax=SpectrumVariables['FMAX']) mel_spec_db = np.float32(librosa.power_to_db(mel_spec_power, ref=np.max)) mel_spec_db-=mel_spec_db.min() mel_spec_db/=mel_spec_db.max() im = np.uint8(cm.gist_earth(mel_spec_db)*255)[:,:,:3] if(im.shape[1]<Input_Resolution): return 0 #CallBack(im) #return 0 imagesTensor = transforms.Compose( [transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])(im[:,-224:,:]) outputs = model(Variable(imagesTensor, requires_grad=False).unsqueeze(0)) outputs = F.softmax(outputs) prob, predicted = torch.topk(outputs,len(classes)) CallBack(predicted[0].detach().numpy(),prob[0].detach().numpy(),classes)
def bulb_image(self, degree=8, observer_position=None, counter=0): """Returns an array with the color values for the pixels in a 2D image grid""" if observer_position is None: observer_position = np.array([0., 0., 3.]) # the power n used in the recursive formula V --> V^n + C any degree >= 0 works, # but smaller degree uses more iterations self.deg = degree # literally the position in space the observer would be in resultant png. # Used for ray tracing source position. self.obpos = observer_position plane_points = self.get_plane_points() # get plane points directions = self.get_directions( plane_points) # get directions to plane points from origin image = self.trace(directions) image = image.reshape(self.width, self.height) arraymax = np.amax(image) # rescale colorvalues so picture is brighter. Array maximum * 1//arraymax is 1 so it will be white image = (1 // arraymax) * image img = Image.fromarray(np.uint8(cm.gist_earth(image) * 255)) if not os.path.exists("frames"): os.makedirs("frames") im = img.save( 'frames/frame{}.png'.format(counter)) # index of generated images
def convert(filename): filename = os.path.join(static_path, filename) inp_image = np.array(Image.open(filename)) print('Segmenting...\n') img_pred = enhance(inp_image).reshape(192, 256) img_crop = get_segment_crop(img=inp_image, mask=img_pred) print('Segmented!\n') im_1 = Image.fromarray(np.uint8(cm.gist_earth(img_pred) * 255)) im_1 = im_1.convert("L") im_1.save(os.path.join(static_path, 'segmented.bmp')) src = cv2.cvtColor(inp_image, cv2.COLOR_RGB2GRAY).flatten() src_mask = enhance(inp_image).flatten() for i in range(len(src_mask)): if src_mask[i] == 0: src[i] = 0 src = src.reshape(192, 256) src = cv2.cvtColor(src, cv2.COLOR_GRAY2RGB) src = Image.fromarray(np.array(src)) src = src.convert("RGB") src.save(os.path.join(static_path, 'cropped.bmp')) print("Cropped!\n") dim = (256, 192) im_2 = cv2.resize(img_crop, dim, interpolation=cv2.INTER_AREA) im_2 = Image.fromarray(im_2) im_2 = im_2.convert("RGB") im_2.save(os.path.join(static_path, 'zoomed.bmp')) print("Zoomed!\n")
def GenerateSpectrums(MainFile): SpectrumVariables = {} with open('../SpectrumVarialbes.csv', newline='') as csvfile: reader = csv.DictReader(csvfile) for row in reader: for k in row: SpectrumVariables[k] = int(row[k]) x, sample_rate_in = librosa.load(MainFile, mono=True) audio_data = librosa.resample(x, sample_rate_in, SpectrumVariables['SAMPLE_RATE']) mel_spec_power = librosa.feature.melspectrogram( audio_data, sr=SpectrumVariables['SAMPLE_RATE'], n_fft=SpectrumVariables['N_FFT'], hop_length=SpectrumVariables['HOP_LENGTH'], n_mels=SpectrumVariables['N_MELS'], power=SpectrumVariables['POWER'], fmin=SpectrumVariables['FMIN'], fmax=SpectrumVariables['FMAX']) mel_spec_db = np.float32(librosa.power_to_db(mel_spec_power, ref=np.max)) mel_spec_db -= mel_spec_db.min() mel_spec_db /= mel_spec_db.max() im = np.uint8(cm.gist_earth(mel_spec_db) * 255)[:, :, :3] ArrayofPictures = [] RESOLUTION = SpectrumVariables['RESOLUTION'] for i in range(int(np.floor(im.shape[1] / RESOLUTION))): startx = RESOLUTION * i stopx = RESOLUTION * (i + 1) ArrayofPictures.append(im[:, startx:stopx, :]) return ArrayofPictures
def sendImage(url): cam = cv2.VideoCapture(0) img_counter = 0 ret, frame = cam.read() img_name = "opencv_frame_{}.png".format(img_counter) gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) ret, bw = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU) imSmall = cv2.resize(bw, (480, 360)) cv2.imwrite(img_name, imSmall) im = Image.fromarray(np.uint8(cm.gist_earth(imSmall) * 255)) postcard = Image.open("postcard.png") im.paste(postcard, (0, 0), postcard) fnt = ImageFont.truetype('lucon.ttf', 50) d = ImageDraw.Draw(im) d.text((25, 100), url, font=fnt, fill=(255, 255, 255)) d.text((30, 95), url, font=fnt, fill=(0, 0, 0)) im = im.transpose(method=Image.ROTATE_90) im.save('test.png') print("{} written!".format(img_name)) # im = Image.open(img_name) binary = p.toBinary(im) data = p.convert(binary) #print(p.output(data)) cam.release() ##### TRANSMISSION usbport = 'COM3' # Set up serial baud rate ser = serial.Serial(usbport, 115200, timeout=1) sleep(2) # for j in range(480): # ser.write('<'.encode()) # txt = b'' # for i in range(45): # txt += struct.pack('>B', data[i][j]) # print('Sending "{}"'.format(txt)) # ser.write(txt) # ser.write('>'.encode()) # # s = ser.readline() # Get result from arduino # print('Readback "{}"'.format(s)) ser.write('('.encode()) txt = b'' for j in range(480): for i in range(45): txt += struct.pack('>B', data[i][j]) print('Sending "{}"'.format(txt)) ser.write(txt) ser.write(')'.encode()) sleep(0.1) s = ser.readline() # Get result from arduino print('Readback "{}"'.format(s))
def get_colors(self, qty): qty = np.power(qty / qty.max(), 1.0 / CONTRAST) if COLORMAP == 0: rgba = cm.gray(qty, alpha=ALPHA) elif COLORMAP == 1: rgba = cm.afmhot(qty, alpha=ALPHA) elif COLORMAP == 2: rgba = cm.hot(qty, alpha=ALPHA) elif COLORMAP == 3: rgba = cm.gist_heat(qty, alpha=ALPHA) elif COLORMAP == 4: rgba = cm.copper(qty, alpha=ALPHA) elif COLORMAP == 5: rgba = cm.gnuplot2(qty, alpha=ALPHA) elif COLORMAP == 6: rgba = cm.gnuplot(qty, alpha=ALPHA) elif COLORMAP == 7: rgba = cm.gist_stern(qty, alpha=ALPHA) elif COLORMAP == 8: rgba = cm.gist_earth(qty, alpha=ALPHA) elif COLORMAP == 9: rgba = cm.spectral(qty, alpha=ALPHA) return rgba
def infere_Class_For_File(FilePath): OutPredictArray=[] OutProbArray=[] N_FFT=SpectrumVariables["N_FFT"] HOP_LENGTH= SpectrumVariables["HOP_LENGTH"] FMIN=SpectrumVariables["FMIN"] FMAX=SpectrumVariables["FMAX"] N_MELS=SpectrumVariables["N_MELS"] POWER=SpectrumVariables["POWER"] RESOLUTION =SpectrumVariables["RESOLUTION"] Audio_data ,sample_rate_in = librosa.load(FilePath,mono=True) mel_spec_power = librosa.feature.melspectrogram(Audio_data, sr=SamplingRate, n_fft=N_FFT, hop_length=HOP_LENGTH, n_mels=N_MELS, power=POWER, fmin=FMIN,fmax=FMAX) mel_spec_db = np.float32(librosa.power_to_db(mel_spec_power, ref=np.max)) mel_spec_db-=mel_spec_db.min() mel_spec_db/=mel_spec_db.max() im = np.uint8(cm.gist_earth(mel_spec_db)*255)[:,:,:3] for i in range(int(np.floor(im.shape[1]/RESOLUTION))): startx=RESOLUTION*i stopx=RESOLUTION*(i+1) OutputImage = im[:,startx:stopx,:] imagesTensor = transforms.Compose([transforms.ToPILImage(), transforms.ToTensor(), transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])(OutputImage) imagesTensor = Variable(imagesTensor, requires_grad=False) testImages = imagesTensor.unsqueeze(0) outputs = model(testImages) outputs = F.softmax(outputs) prob, predicted = torch.topk(outputs,len(classes),sorted=False) OutPredictArray.append(predicted.numpy()[0]) OutProbArray.append(prob.detach().numpy()[0]) return OutPredictArray, OutProbArray, classes
def plot_img_and_mask(img, mask, filename): fig, ax = plt.subplots(1, 3) indices_list = np.where(np.all(mask != False, axis=-1)) print("excluded indices are", indices_list) mask[indices_list] = 0 print(mask) cv2.imwrite('/content/drive/My Drive/Colab Notebooks/S15AB/m.jpg', np.uint8(cm.gist_earth(mask)) * 255)
def save(self, tick_data): frame = self.step // 10 Image.fromarray(tick_data['rgb']).save(self.save_path / 'rgb' / ('%04d.png' % frame)) Image.fromarray( cm.gist_earth(self.lidar_processed[0].cpu().numpy()[0, 0], bytes=True)).save(self.save_path / 'lidar_0' / ('%04d.png' % frame)) Image.fromarray( cm.gist_earth(self.lidar_processed[0].cpu().numpy()[0, 1], bytes=True)).save(self.save_path / 'lidar_1' / ('%04d.png' % frame)) outfile = open(self.save_path / 'meta' / ('%04d.json' % frame), 'w') json.dump(self.pid_metadata, outfile, indent=4) outfile.close()
def show_only_heights(screen, state: VisState, settings: VisSettings) -> Generator: height_array = state.selected_area_height_map - state.selected_area_height_map.min() height_array = (height_array // (height_array.max() / 255)).astype("int32") image = Image.fromarray(numpy.uint8(cm.gist_earth(height_array) * 255)) state.pygame_img = pygame.image.fromstring(image.tobytes(), image.size, image.mode) state.pygame_img = pygame.transform.scale( state.pygame_img, [int(state.pygame_img.get_rect().size[i] * state.float_pixel_size[i]) for i in (0, 1)] ) screen.blit(state.pygame_img, (0, 0)) yield
def make_2d(x_seq, y_seq, alphabet, file_name, out_dir, labels, matplot, pil, array_flag): """ fun plots 2D metrics of watson-crick binding rules of sequence x and y as heatmap parameters x_seq=sequecne on x axis y_seq=sequence on y axis alphabet=2D matrix file_name=image file name out_dir=target directory labels=labels ticks as nt sequences (boolean) matplot=generate matplot images (boolean) pil=generate pil image (boolean) array_flag=return np array (boolean) """ # set output dir if out_dir: file_name = os.path.join(out_dir, file_name) # Create binding site - mirna interaction metrics array = make_set_hm(x_seq, y_seq, alphabet) # Default heatmap: just a visualization of this square matrix if matplot: plt.imshow(array) plt.savefig(file_name) elif pil: img = Image.fromarray(np.uint8(cm.gist_earth(array) * 255)) img.save(f"{file_name}.png") elif array_flag: return array else: A = len(x_seq) B = len(y_seq) df = pd.DataFrame(array, index=list(x_seq), columns=list(y_seq)) FIG, AX = plt.subplots(figsize=(B, A)) AX = sns.heatmap( df, xticklabels=labels, yticklabels=labels, annot=False, cbar=False, cmap="Blues", # vmin=0, # vmax=1, ) FIG.savefig(f"{file_name}.png") plt.cla() plt.close(FIG) return array
def main(): cap = cv2.VideoCapture(0) i = 0 while True: ret, frame = cap.read() bw_img = cv2.cvtColor(frame, cv.CV_BGR2GRAY) if i == 15: im = Image.fromarray(np.uint8(cm.gist_earth(bw_img)*255)) print pytesseract.image_to_string(im) i = 0 i += 1 cv2.imshow("camera", bw_img) c = cv2.waitKey(1)
def click_estimate_density2(): global my_image newWindow = Toplevel(root) newWindow.geometry('600x600+800+100') newWindow.iconbitmap("e:\cnts_sem\icon3.ico") newWindow.attributes("-topmost", True) selector = Label(newWindow, text="Original Image").pack() newWindow.filename = filedialog.askopenfilename(initialdir="/", title="Select a file", filetypes=(("png files", "*.png"), ("all files", "*.*"))) def update(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text = sel, font =("Courier", 14)) edges = cv2.Canny(image,v1.get(),200) im = Image.fromarray(np.uint8(cm.gist_earth(edges)*255)) my_image = ImageTk.PhotoImage(im) newWindow = Toplevel(root) newWindow.geometry('600x600+800+100') newWindow.iconbitmap("..\cnts_sem\icon3.ico") newWindow.attributes("-topmost", True) selector = Label(newWindow, text="XXXX").pack() my_image_label = Label(newWindow,image=my_image).pack() newWindow.pack() a = 100 v1 = DoubleVar() image = skimage.io.imread(fname=newWindow.filename, as_gray=False) edges = cv2.Canny(image, a,200) im = Image.fromarray(np.uint8(cm.gist_earth(edges)*255)) my_image = ImageTk.PhotoImage(im) my_image_label = Label(newWindow,image=my_image).pack() s1 = Scale(newWindow, variable = v1, from_ = 1, to = 100, orient = HORIZONTAL) l3 = Label(newWindow, text = "Horizontal Scaler") b1 = Button(newWindow, text ="Adjust", command = update, bg = "yellow") s1.pack(anchor = CENTER) l3.pack() b1.pack(anchor = CENTER) l1 = Label(newWindow) l1.pack()
def pad_image(image): # assuming image has one dim = 256 zero_matrix = np.zeros((256, 256)) padded_image = Image.fromarray(np.uint8(cm.gist_earth(zero_matrix) * 255)) # convert np array to PIL image width, height = image.size x = 0 y = 0 if width == 256: y = randint(0, 256 - height) elif height == 256: x = randint(0, 256 - width) padded_image.paste(image, (x, y)) return padded_image
def openBinary(self): global binary_val global last global last_operation binary_val = self.horizontalSlider.value() self.Binary.setText(str(binary_val)) originalImage = cv2.imread(location,0) _,thresh1 = cv2.threshold(originalImage,binary_val,255,cv2.THRESH_BINARY) im = Image.fromarray(np.uint8(cm.gist_earth(thresh1)*255)) qim = ImageQt(im) last = binary_val last_operation = "Binary" self.image_2.setPixmap(QtGui.QPixmap.fromImage(qim))
def __getitem__(self, idx): """ Read one or a list receipt image and the correspondent json file parameters : ----------- - idx : index of the image to read in the directory containing the images and the json files. """ if torch.is_tensor(idx): idx = idx.tolist() one_receipt_image = Image.open( self.receipts_images[idx]).convert("RGB") w, h = one_receipt_image.size # 0: other, 1: total: boxes boxes = build_bboxes(self.receipts_json[idx]) grid, self.dictionary = build_Grid(one_receipt_image, self.dictionary) mask = build_mask(boxes, w, h) mask = Image.fromarray(np.uint8(cm.gist_earth(mask) * 255)).convert("L") grid = Image.fromarray(np.uint8(cm.gist_earth(grid) * 255)).convert("L") if self.transforms is not None: img, grid, mask = self.transforms(one_receipt_image, grid, mask) mask = np.where(np.array(mask) > 0, 1, 0) image = torch.as_tensor(np.array(one_receipt_image), dtype=torch.float32) mask = torch.as_tensor(mask, dtype=torch.long).unsqueeze(0) grid = torch.as_tensor(np.array(grid), dtype=torch.long) return image, grid, mask
def update(): sel = "Horizontal Scale Value = " + str(v1.get()) l1.config(text = sel, font =("Courier", 14)) edges = cv2.Canny(image,v1.get(),200) im = Image.fromarray(np.uint8(cm.gist_earth(edges)*255)) my_image = ImageTk.PhotoImage(im) newWindow = Toplevel(root) newWindow.geometry('600x600+800+100') newWindow.iconbitmap("..\cnts_sem\icon3.ico") newWindow.attributes("-topmost", True) selector = Label(newWindow, text="XXXX").pack() my_image_label = Label(newWindow,image=my_image).pack() newWindow.pack()
def make_gif_slices(self, vol, name='test', timestr=None, length=None): images = [] gifdir = 'figures/gif_dir/' if timestr is not None: if not os.path.isdir(gifdir + timestr): os.mkdir(gifdir + timestr) gifdir += timestr + '/' print('Saving to ', gifdir) if length is None: length = len(nbody.redshift_bins) for i in xrange(length): plooop = (cm.gist_earth( (vol[i, :, :] + 1) / 2) * 255).astype('uint8') images.append(Image.fromarray(plooop).resize((512, 512))) imageio.mimsave(gifdir + name + '.gif', images, fps=2)
def openTrunc(self): global trunc_val global last global last_operation trunc_val = self.horizontalSlider_3.value() self.thresh_trunc.setText(str(trunc_val)) originalImage = cv2.imread(location,0) _,thresh1 = cv2.threshold(originalImage,trunc_val,255,cv2.THRESH_TRUNC) im = Image.fromarray(np.uint8(cm.gist_earth(thresh1)*255)) qim = ImageQt(im) last = trunc_val last_operation = "Trunc" self.image_2.setPixmap(QtGui.QPixmap.fromImage(qim))
def compare(model, filename): """ Tests model on BSR dataset. Output : dictionnary containing raw image, groundtruth and model reconstructed image """ filename = filename[:-4] dict = scipy.io.loadmat(path_truth + filename) mat = dict["groundTruth"] mat = mat[0, 4]['Segmentation'][0][0] im_truth = transforms.Resize(resolution)(pl.Image.fromarray( np.uint8(cm.gist_earth(mat) * 255))) im_raw = transforms.Resize(resolution)(pl.Image.open(path_raw + filename + '.jpg')) tensor = transforms.ToTensor()(im_raw).unsqueeze_(0).to(DEVICE) im_model = showimg(model(tensor)[1]) return {"raw": im_raw, "model": im_model, "truth": im_truth}
def make_zslice_gif(self, model, timestr, epoch, zs=None, fps=2): fixed_z = torch.randn(1, 201, 1, 1, 1).float() zslices = np.zeros((len(nbody.redshift_bins), 64, 64)) images = [] iteration = nbody.redshift_bins if zs is not None: iteration = zs for i in xrange(len(iteration)): fixed_z[:, -1] = iteration[i] gen_samp = model(fixed_z).detach().numpy() ploop = (cm.gist_earth( (gen_samp[0][0][10, :, :] + 1) / 2) * 255).astype('uint8') images.append(Image.fromarray(ploop).resize((512, 512))) imageio.mimsave('figures/gif_dir/' + timestr + '/zslicegif_epoch_' + str(epoch) + '.gif', images, fps=fps)
def export_image(self, idx=100): img, label = self.val_data.images[:,idx,:], self.val_data.labels[0][idx] img = img.transpose(1, 0) label -= 1 label = self.decoder.to_string(label) from PIL import Image from matplotlib import cm im = Image.fromarray(np.uint8(cm.gist_earth(img)*255)) im.save('test_image.png') img = img.transpose(1, 0) img = np.reshape(img, (-1, 1)) np.savetxt("test_image.txt", img, fmt='%.10f') f = open('test_image_gt.txt','w') f.write(label) f.close() print("Exported image with label = {}".format(label))
def set_img(self, img): self.shape = img.shape image = Image.fromarray(np.uint8(cm.gist_earth(img) * 255)) for x, box in enumerate(self.bndbxes): draw = ImageDraw.Draw(image) draw.rectangle([(box[0], box[1]), (box[2], box[3])], outline="black", width=5) # cv2.imwrite('backend/summary/' + str(i) +"_"+str(s.bndbx_timestamps[x]) +".jpg",im_np[box[1]:box[3],box[0]:box[2]]) self.img = image.convert('L') self.img = np.array(np.array(self.img)) print(self.shape) # img = np.transpose(img, (1, 0, 2)).copy() qimage = QImage(self.img, self.shape[1], self.shape[0], QImage.Format_Grayscale8) self.img = QPixmap(qimage)
def resize(image, target_width, target_height): if target_height / image.shape[0] > target_width / image.shape[1]: top_height = math.floor( (target_height - image.shape[0] * target_width / image.shape[1]) / 2) temp_top = np.ones((top_height, image.shape[1])) image = np.concatenate((temp_top, image, temp_top), axis=0) else: left_width = math.floor( (target_width - image.shape[1] * target_height / image.shape[0]) / 2) temp_left = np.ones((image.shape[0], left_width)) image = np.concatenate((temp_left, image, temp_left), axis=1) temp = Image.fromarray(np.uint8(cm.gist_earth(image) * 255)) temp = temp.resize((target_width, target_height), resample=Image.BICUBIC) # temp.show() temp = np.asarray(temp).astype(np.float32) / 255 # print(temp.shape) temp = rgb_to_gray(temp[:, :, :-1]) # plt.imshow(temp, interpolation='nearest') # plt.show() return temp
def export_image(self): random.seed() idx = random.randint(0, self.val_data.images.shape[1] - 1) # idx = 100 img, label = self.val_data.images[:, idx, :], self.val_data.labels[0][idx] inp = torch.from_numpy(img) inp = inp.unsqueeze(1) inp = Variable(inp, requires_grad=False) out = self.model(inp) out = self.decoder.decode(out, self.val_data.input_lengths, self.val_data.label_lengths) out = self.decoder.to_string(out) img = img.transpose(1, 0) label -= 1 label = self.decoder.to_string(label) assert label == out from PIL import Image, ImageOps from matplotlib import cm img1 = (img + 1) / 2. im = Image.fromarray(np.uint8(cm.gist_earth(img1) * 255)).convert('L') im = ImageOps.invert(im) im.save('test_image.png') img = img.transpose(1, 0) img = np.reshape(img, (-1, 1)) np.savetxt("test_image.txt", img, fmt='%.10f') f = open('test_image_gt.txt', 'w') f.write(label) f.close() print("Prediction on the image = {}".format(out)) print("Label of exported image = {}".format(label))
def array_to_cam(arr): cam_pil = Image.fromarray(np.uint8(cm.gist_earth(arr) * 255)).convert("RGB") return cam_pil
def createImage(raster, name): raster[raster > np.percentile(raster, 95)] = np.percentile(raster, 95) raster /= raster.max() im = Image.fromarray(np.uint8(cm.gist_earth(raster) * 255)) im.save(name)
def get_img(self, iters): iters = 1 + np.log(iters / float(self._max_iter)) im = Image.fromarray(cm.gist_earth(iters, bytes=True)) return im
def PIL_render(img): return Image.fromarray(cm.gist_earth(img/np.max(img), bytes=True))
if str(bbl) in bbls: block, lot, floors = bbls[str(bbl)] h = np.percentile(heights, 75) bbls[str(bbl)].append(h) bbls[str(bbl)].append(h/floors if floors > 0 else 0) #f.write(',',join([block, lot, np.percentile(heights, 75)]) + '\n') np.save(step2, bbls) else: print "loading", step2 bbls = np.load(step2).item() print bbls["389752"] fraster = np.zeros((5000,5000)) for i in range(fraster.shape[0]): for j in range(fraster.shape[1]): if str(braster[i][j]) in bbls: bbl = str(braster[i][j]) if not np.isnan(bbls[bbl][4]): fraster[i][j] = bbls[bbl][4] print np.max(fraster) fraster[fraster>np.percentile(fraster, 95)] = np.max(fraster) fraster /= np.max(fraster) fraster *= 255 fraster = np.uint8(fraster) im = Image.fromarray(np.uint8(cm.gist_earth(fraster)*255)) im.save('floorheights.jpg')
def makeLut(ncolors): lut_temp=cm.gist_earth(np.arange(ncolors))*256 return lut_temp[::,0:3].astype(int)