Python matplotlib.image.imread() Examples
The following are 30
code examples of matplotlib.image.imread().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
matplotlib.image
, or try the search function
.
Example #1
Source File: visualize_coco_detections.py From MOTSFusion with MIT License | 7 votes |
def visualize(img_id): img_descriptor = coco.loadImgs(img_id) file_name = coco_data_folder + "val/" + img_descriptor[0]['file_name'] fig, ax = plt.subplots(1) img = mpimg.imread(file_name) ax.imshow(img) gt_ann_ids = coco.getAnnIds(imgIds=[img_id]) gt_anns = coco.loadAnns(gt_ann_ids) dets = detections_by_imgid[img_id] print("Image", img_id, "Dets", len(dets), "GT", len(gt_anns)) for gt in gt_anns: draw_box(ax, gt['bbox'], 'r', gt['category_id'], 1.0) for det in dets: draw_box(ax, det['bbox'], 'b', det['category_id'], det['score']) plt.show()
Example #2
Source File: helpers.py From Advanced_Lane_Lines with MIT License | 6 votes |
def wrap_images(src, dst): """ apply the wrap to images """ # load M, Minv img_size = (1280, 720) pickle_file = open("../helper/trans_pickle.p", "rb") trans_pickle = pickle.load(pickle_file) M = trans_pickle["M"] Minv = trans_pickle["Minv"] # loop the file folder image_files = glob.glob(src+"*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) image_wraped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR) file_name = file.split("\\")[-1] print(file_name) out_image = dst+file_name print(out_image) # no need to covert RGB to BGR since 3 channel is same image_wraped = cv2.cvtColor(image_wraped, cv2.COLOR_RGB2BGR) cv2.imwrite(out_image, image_wraped)
Example #3
Source File: plot_generator.py From mpl-probscale with BSD 3-Clause "New" or "Revised" License | 6 votes |
def create_thumbnail(infile, thumbfile, width=300, height=300, cx=0.5, cy=0.5, border=4): baseout, extout = op.splitext(thumbfile) im = image.imread(infile) rows, cols = im.shape[:2] x0 = int(cx * cols - .5 * width) y0 = int(cy * rows - .5 * height) xslice = slice(x0, x0 + width) yslice = slice(y0, y0 + height) thumb = im[yslice, xslice] thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 dpi = 100 fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) ax.imshow(thumb, aspect='auto', resample=True, interpolation='bilinear') fig.savefig(thumbfile, dpi=dpi) return fig
Example #4
Source File: image.py From FaceDetection with MIT License | 6 votes |
def __init__(self, fileName = None, label = None, Mat = None): if fileName != None: self.imgName = fileName self.img = image.imread(fileName) if len(self.img.shape) == 3: self.img = self.img[:,:, 1] else: assert Mat != None self.img = Mat self.label = label #self.stdImg = Image._normalization(self.img) #self.iimg = Image._integrateImg(self.stdImg) #self.vecImg = self.iimg.transpose().flatten() self.vecImg = Image._integrateImg( Image._normalization(self.img) ).transpose().flatten()
Example #5
Source File: graph_tools.py From tools with BSD 3-Clause "New" or "Revised" License | 6 votes |
def graphviz_plot(graph, fname="tmp_dotgraph.dot", show=True): if os.path.exists(fname): print("WARNING: Overwriting existing file {} for new plots".format(fname)) f = open(fname,'w') f.writelines('digraph G {\nnode [width=.3,height=.3,shape=octagon,style=filled,color=skyblue];\noverlap="false";\nrankdir="LR";\n') for i in graph: for j in graph[i]: s= ' '+ i s += ' -> ' + j + ' [label="' + str(graph[i][j]) + '"]' s+=';\n' f.writelines(s) f.writelines('}') f.close() graphname = fname.split(".")[0] + ".png" pe(["dot", "-Tpng", fname, "-o", graphname]) if show: plt.imshow(mpimg.imread(graphname)) plt.show()
Example #6
Source File: BuildingHeight.py From procedural_city_generation with Mozilla Public License 2.0 | 6 votes |
def __init__(self, savename, imagename): self.path=os.path.dirname(procedural_city_generation.__file__) try: with open(self.path+"/temp/"+savename+ "_heightmap.txt", 'r') as f: self.border=[eval(x) for x in f.read().split("_")[-2:] if x is not ''] except IOError: print("Run the previous steps in procedural_city_generation first! If this message persists, run the \"clean\" command") return if imagename == "diffused": print("Using diffused version of population density image") with open(self.path+"/temp/"+savename+ "_densitymap.txt", 'r') as f: densityname=f.read() print("Population density image is being set up") self.img=self.setupimage(self.path+"/temp/"+densityname) print("Population density image setup is finished") return else: print("Looking for image in procedural_city_generation/inputs/buildingheight_pictures") import matplotlib.image as mpimg self.img=mpimg.imread(self.path +"/inputs/buildingheight_pictures/" + imagename) print("Image found")
Example #7
Source File: data.py From UnFlow with MIT License | 6 votes |
def compute_statistics(self, files): """Use welford's method to compute mean and variance of the given dataset. See https://en.wikipedia.org/wiki/Algorithms_for_calculating_variance#Online_algorithm.""" assert len(files) > 1 n = 0 mean = np.zeros(3) M2 = np.zeros(3) for j, filename in enumerate(files): #TODO ensure the pixel values are 0..255 im = np.reshape(mpimg.imread(filename) * 255, [-1, 3]) for i in range(np.shape(im)[1]): n = n + 1 delta = im[i] - mean mean += delta / n M2 += delta * (im[i] - mean) sys.stdout.write('\r>> Processed %.1f%%' % ( float(j) / float(len(files)) * 100.0)) sys.stdout.flush() var = M2 / (n - 1) stddev = np.sqrt(var) return np.float32(mean), np.float32(stddev)
Example #8
Source File: car_nocar.py From RoboND-Perception-Intro with MIT License | 6 votes |
def extract_features(imgs, hist_bins=32, hist_range=(0, 256)): # Create a list to append feature vectors to features = [] # Iterate through the list of images for file in imgs: # Read in each one by one image = mpimg.imread(file) # Apply color_hist() hist_features = color_hist(image, nbins=hist_bins, bins_range=hist_range) # Append the new feature vector to the features list features.append(hist_features) # Return list of feature vectors return features # Read in car and non-car images
Example #9
Source File: WatertoolsTest.py From procedural_city_generation with Mozilla Public License 2.0 | 6 votes |
def main(): import matplotlib.pyplot as plt import matplotlib.image as mpimg import sys, os sys.path.append("../../..") import procedural_city_generation from procedural_city_generation.roadmap.config_functions.Watertools import Watertools import Image import numpy as np img=np.dot(mpimg.imread(os.getcwd() + "/resources/manybodies.png")[..., :3], [0.299, 0.587, 0.144]) w=Watertools(img) plt.imshow(img, cmap="gray") plt.show() f=w.flood(0.95, np.array([80, 2])) plt.imshow(f, cmap="gray") plt.show()
Example #10
Source File: view_perspective.py From Advanced_Lane_Lines with MIT License | 6 votes |
def test(): pickle_file = open("trans_pickle.p", "rb") trans_pickle = pickle.load(pickle_file) M = trans_pickle["M"] Minv = trans_pickle["Minv"] img_size = (1280, 720) image_files = glob.glob("../output_images/undistort/*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) warped = cv2.warpPerspective(img, M, img_size, flags=cv2.INTER_LINEAR) file_name = file.split("\\")[-1] print(file_name) out_image = "../output_images/perspect_trans/"+file_name print(out_image) # convert to opencv BGR format warped = cv2.cvtColor(warped, cv2.COLOR_RGB2BGR) cv2.imwrite(out_image, warped)
Example #11
Source File: test_image.py From neural-network-animation with MIT License | 6 votes |
def test_imsave_color_alpha(): # Test that imsave accept arrays with ndim=3 where the third dimension is # color and alpha without raising any exceptions, and that the data is # acceptably preserved through a save/read roundtrip. from numpy import random random.seed(1) data = random.rand(256, 128, 4) buff = io.BytesIO() plt.imsave(buff, data) buff.seek(0) arr_buf = plt.imread(buff) # Recreate the float -> uint8 -> float32 conversion of the data data = (255*data).astype('uint8').astype('float32')/255 # Wherever alpha values were rounded down to 0, the rgb values all get set # to 0 during imsave (this is reasonable behaviour). # Recreate that here: for j in range(3): data[data[:, :, 3] == 0, j] = 1 assert_array_equal(data, arr_buf)
Example #12
Source File: image_process.py From Advanced_Lane_Lines with MIT License | 6 votes |
def test_yellow_white_thresh_images(src, dst, y_low=(10,50,0), y_high=(30,255,255), w_low=(180,180,180), w_high=(255,255,255)): """ apply the thresh to images in a src folder and output to dst foler """ image_files = glob.glob(src+"*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) image_threshed = yellow_white_thresh(img, y_low, y_high, w_low, w_high) file_name = file.split("\\")[-1] print(file_name) out_image = dst+file_name print(out_image) # convert binary to RGB, *255, to visiual, 1 will not visual after write to file image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB) # HSV = cv2.cvtColor(img, cv2.COLOR_RGB2HSV) # V = HSV[:,:,2] # brightness = np.mean(V) # info_str = "brightness is: {}".format(int(brightness)) # cv2.putText(image_threshed, info_str, (50,700), cv2.FONT_HERSHEY_SIMPLEX,2,(0,255,255),2) cv2.imwrite(out_image, image_threshed)
Example #13
Source File: image_process.py From Advanced_Lane_Lines with MIT License | 6 votes |
def test_yellow_grid_thresh_images(src, dst, y_low=(10,50,0), y_high=(30,255,255), sx_thresh=(20, 100)): """ apply the thresh to images in a src folder and output to dst foler """ image_files = glob.glob(src+"*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) image_threshed = yellow_grid_thresh(img, y_low, y_high, sx_thresh) file_name = file.split("\\")[-1] print(file_name) out_image = dst+file_name print(out_image) # convert binary to RGB, *255, to visiual, 1 will not visual after write to file image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB) cv2.imwrite(out_image, image_threshed)
Example #14
Source File: image_process.py From Advanced_Lane_Lines with MIT License | 6 votes |
def test_color_grid_thresh_dynamic(src, dst, s_thresh, sx_thresh): """ apply the thresh to images in a src folder and output to dst foler """ image_files = glob.glob(src+"*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) image_threshed = color_grid_thresh_dynamic(img, s_thresh=s_thresh, sx_thresh=sx_thresh) file_name = file.split("\\")[-1] print(file_name) out_image = dst+file_name print(out_image) # convert binary to RGB, *255, to visiual, 1 will not visual after write to file image_threshed = cv2.cvtColor(image_threshed*255, cv2.COLOR_GRAY2RGB) cv2.imwrite(out_image, image_threshed)
Example #15
Source File: helpers.py From Advanced_Lane_Lines with MIT License | 6 votes |
def undistort_images(src, dst): """ undistort the images in src folder to dst folder """ # load dst, mtx pickle_file = open("../camera_cal/camera_cal.p", "rb") dist_pickle = pickle.load(pickle_file) mtx = dist_pickle["mtx"] dist = dist_pickle["dist"] pickle_file.close() # loop the image folder image_files = glob.glob(src+"*.jpg") for idx, file in enumerate(image_files): print(file) img = mpimg.imread(file) image_dist = cv2.undistort(img, mtx, dist, None, mtx) file_name = file.split("\\")[-1] print(file_name) out_image = dst+file_name print(out_image) image_dist = cv2.cvtColor(image_dist, cv2.COLOR_RGB2BGR) cv2.imwrite(out_image, image_dist)
Example #16
Source File: auto_send_emoji.py From spider_python with Apache License 2.0 | 5 votes |
def show_image(self, filename): lena = mpimg.imread(filename) plt.imshow(lena) # 显示图片 plt.axis('off') # 不显示坐标轴 plt.show()
Example #17
Source File: visualize.py From Audio-Vision with MIT License | 5 votes |
def get_image_features(image_file_name): ''' Runs the given image_file to VGG 16 model and returns the weights (filters) as a 1, 4096 dimension vector ''' # image_features = np.zeros((1, 4096)) image_features = np.zeros((1,4096)) # Magic_Number = 4096 > Comes from last layer of VGG Model # Since VGG was trained as a image of 224x224, every new image # is required to go through the same transformation im=cv2.imread(image_file_name) if im is None: raise Exception("Incorrect path") # cv2.imshow('Image',im) # cv2.waitKey(0) im = cv2.resize(im, (224,224)).astype(np.float32) mean_pixel = [103.939, 116.779, 123.68] im = im.astype(np.float32, copy=False) for c in range(3): im[:, :, c] = im[:, :, c] - mean_pixel[c] im = im.transpose((2,0,1)) # convert the image to RGBA # this axis dimension is required because VGG was trained on a dimension # of 1, 3, 224, 224 (first axis is for the batch size # even though we are using only one image, we have to keep the dimensions consistent im = np.expand_dims(im, axis=0) x = preprocess_input(im) image_features[0,:] = get_image_model().predict(x)[0] return image_features
Example #18
Source File: train_CGAN.py From deep-generative-models with MIT License | 5 votes |
def trainCGAN(data,learning_rate,epochs,batch_size,im_dim,num_filters,latent_dimensions, g_factor,drop_rate): # import data print("importing training data") if data == "fashion_mnist": (train_images, _), (_, _) = tf.keras.datasets.fashion_mnist.load_data() elif data == "mnist": (train_images, _), (_, _) = tf.keras.datasets.mnist.load_data() elif data == "faces": train_images = [resize(mpimg.imread(file),(28,28)) for file in glob.glob("./data/faces/*")] train_images = np.asarray(train_images,dtype="float32") train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32') else: raise NameError("unknown data type: %s" % data) if data == "mnist" or data == "fashion_mnist": train_images = train_images.reshape(train_images.shape[0], 28, 28, 1).astype('float32') train_images /= 255. # create log directory current_time = getCurrentTime()+"_"+re.sub(",","_",str(latent_dimensions))+"_"+data+"_cgan" os.makedirs("pickles/"+current_time) # create model model = CGAN(latent_dim=latent_dimensions, epochs = epochs, batch_size = batch_size, learning_rate = learning_rate, im_dim = im_dim, n_filters = num_filters, g_factor = g_factor, drop_rate = drop_rate) model.train(train_images) # save model model.save_weights("pickles/"+current_time+"/cgan") csvfile = open('pickles/'+ current_time + '/' + 'log.csv', 'w') fieldnames = ["data", "learning_rate", "epochs", "batch_size", "im_dim", "num_filters", "latent_dimensions", "g_factor", "drop_rate"] writer = csv.DictWriter(csvfile, fieldnames=fieldnames) writer.writeheader() writer.writerow({"data":data, "learning_rate":learning_rate, "epochs":epochs, "batch_size":batch_size, "im_dim":im_dim, "num_filters":num_filters, "latent_dimensions":latent_dimensions, "g_factor":g_factor, "drop_rate":drop_rate}) csvfile.close()
Example #19
Source File: train_RBM.py From deep-generative-models with MIT License | 5 votes |
def trainRBM(data, learning_rate, k1, k2, epochs, batch_size, dims): # import data print("importing training data") if data == "fashion_mnist": fashion_mnist = tf.keras.datasets.fashion_mnist (x_train, _), (_,_) = fashion_mnist.load_data() elif data == "mnist": mnist = tf.keras.datasets.mnist (x_train, _), (_,_) = mnist.load_data() elif data == "faces": x_train = [resize(mpimg.imread(file),(28,28)) for file in glob.glob("data/faces/*")] x_train = np.asarray(x_train) # make images sparse for easier distinctions for img in x_train: img[img < np.mean(img)+0.5*np.std(img)] = 0 else: raise NameError("unknown data type: %s" % data) if data == "mnist" or data == "fashion_mnist": x_train = x_train/255.0 x_train = [tf.cast(tf.reshape(x,shape=(784,1)),"float32") for x in x_train] elif data == "faces": # auto conversion to probabilities in earlier step x_train = [tf.cast(tf.reshape(x,shape=(784,1)),"float32") for x in x_train] # create log directory current_time = getCurrentTime()+"_"+re.sub(",","_",dims)+"_"+data+"_rbm" os.makedirs("pickles/"+current_time) # parse string input into integer list dims = [int(el) for el in dims.split(",")] rbm = RBM(dims[0], dims[1], learning_rate, k1, k2, epochs, batch_size) rbm.persistive_contrastive_divergence_k(x_train) # dump rbm pickle f = open("pickles/"+current_time+"/rbm.pickle", "wb") pickle.dump(rbm, f, protocol=pickle.HIGHEST_PROTOCOL) f.close()
Example #20
Source File: visualize.py From Audio-Vision with MIT License | 5 votes |
def plot(image_file_name): img=mpimg.imread(image_file_name) imgplot = plt.imshow(img) plt.show()
Example #21
Source File: plot_generator.py From py-openaq with MIT License | 5 votes |
def create_thumbnail(infile, thumbfile, width=275, height=275, cx=0.5, cy=0.5, border=4): baseout, extout = op.splitext(thumbfile) im = image.imread(infile) rows, cols = im.shape[:2] x0 = int(cx * cols - .5 * width) y0 = int(cy * rows - .5 * height) xslice = slice(x0, x0 + width) yslice = slice(y0, y0 + height) thumb = im[yslice, xslice] #thumb = im thumb[:border, :, :3] = thumb[-border:, :, :3] = 0 thumb[:, :border, :3] = thumb[:, -border:, :3] = 0 dpi = 100 fig = plt.figure(figsize=(width / dpi, height / dpi), dpi=dpi) ax = fig.add_axes([0, 0, 1, 1], aspect='auto', frameon=False, xticks=[], yticks=[]) ax.imshow(thumb, aspect='auto', resample=True, interpolation='bilinear') fig.savefig(thumbfile, dpi=dpi) return fig
Example #22
Source File: deterministic.py From pygom with GNU General Public License v2.0 | 5 votes |
def get_transition_graph(self, file_name=None, show=True): ''' Returns the transition graph using graphviz Parameters ---------- file_name: str, optional name of the output file, defaults to None show: bool, optional If the graph should be plotted, defaults to True Returns ------- :class:`graphviz.Digraph` ''' dot = _ode_composition.generateTransitionGraph(self, file_name) if show: import matplotlib.image as mpimg import matplotlib.pyplot as plt img = mpimg.imread(io.BytesIO(dot.pipe("png"))) plt.imshow(img) plt.show(block=False) return dot else: return dot # # this is the main ode solver #
Example #23
Source File: test_image.py From neural-network-animation with MIT License | 5 votes |
def test_image_python_io(): fig = plt.figure() ax = fig.add_subplot(111) ax.plot([1,2,3]) buffer = io.BytesIO() fig.savefig(buffer) buffer.seek(0) plt.imread(buffer)
Example #24
Source File: test_agg.py From python3_ios with BSD 3-Clause "New" or "Revised" License | 5 votes |
def test_repeated_save_with_alpha(): # We want an image which has a background color of bluish green, with an # alpha of 0.25. fig = Figure([1, 0.4]) canvas = FigureCanvas(fig) fig.set_facecolor((0, 1, 0.4)) fig.patch.set_alpha(0.25) # The target color is fig.patch.get_facecolor() buf = io.BytesIO() fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Save the figure again to check that the # colors don't bleed from the previous renderer. buf.seek(0) fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Check the first pixel has the desired color & alpha # (approx: 0, 1.0, 0.4, 0.25) buf.seek(0) assert_array_almost_equal(tuple(imread(buf)[0, 0]), (0.0, 1.0, 0.4, 0.250), decimal=3)
Example #25
Source File: test_image.py From neural-network-animation with MIT License | 5 votes |
def test_image_edges(): f = plt.figure(figsize=[1, 1]) ax = f.add_axes([0, 0, 1, 1], frameon=False) data = np.tile(np.arange(12), 15).reshape(20, 9) im = ax.imshow(data, origin='upper', extent=[-10, 10, -10, 10], interpolation='none', cmap='gray' ) x = y = 2 ax.set_xlim([-x, x]) ax.set_ylim([-y, y]) ax.set_xticks([]) ax.set_yticks([]) buf = io.BytesIO() f.savefig(buf, facecolor=(0, 1, 0)) buf.seek(0) im = plt.imread(buf) r, g, b, a = sum(im[:, 0]) r, g, b, a = sum(im[:, -1]) assert g != 100, 'Expected a non-green edge - but sadly, it was.'
Example #26
Source File: single_tuple_train_data.py From DTPP with BSD 2-Clause "Simplified" License | 5 votes |
def readimg(): lena = mpimg.imread("/home/zhujiagang/temporal-segment-networks/yulan.jpg") im =Image.fromarray(np.uint8(lena*255)) im.show()
Example #27
Source File: test_image.py From neural-network-animation with MIT License | 5 votes |
def test_imread_pil_uint16(): img = plt.imread(os.path.join(os.path.dirname(__file__), 'baseline_images', 'test_image', 'uint16.tif')) assert (img.dtype == np.uint16) assert np.sum(img) == 134184960 # def test_image_unicode_io(): # fig = plt.figure() # ax = fig.add_subplot(111) # ax.plot([1,2,3]) # fname = u"\u0a3a\u0a3a.png" # fig.savefig(fname) # plt.imread(fname) # os.remove(fname)
Example #28
Source File: test_image.py From neural-network-animation with MIT License | 5 votes |
def test_imsave(): # The goal here is that the user can specify an output logical DPI # for the image, but this will not actually add any extra pixels # to the image, it will merely be used for metadata purposes. # So we do the traditional case (dpi == 1), and the new case (dpi # == 100) and read the resulting PNG files back in and make sure # the data is 100% identical. from numpy import random random.seed(1) data = random.rand(256, 128) buff_dpi1 = io.BytesIO() plt.imsave(buff_dpi1, data, dpi=1) buff_dpi100 = io.BytesIO() plt.imsave(buff_dpi100, data, dpi=100) buff_dpi1.seek(0) arr_dpi1 = plt.imread(buff_dpi1) buff_dpi100.seek(0) arr_dpi100 = plt.imread(buff_dpi100) assert arr_dpi1.shape == (256, 128, 4) assert arr_dpi100.shape == (256, 128, 4) assert_array_equal(arr_dpi1, arr_dpi100)
Example #29
Source File: pyplot.py From neural-network-animation with MIT License | 5 votes |
def imread(*args, **kwargs): return _imread(*args, **kwargs)
Example #30
Source File: test_agg.py From neural-network-animation with MIT License | 5 votes |
def test_repeated_save_with_alpha(): # We want an image which has a background color of bluish green, with an # alpha of 0.25. fig = Figure([1, 0.4]) canvas = FigureCanvas(fig) fig.set_facecolor((0, 1, 0.4)) fig.patch.set_alpha(0.25) # The target color is fig.patch.get_facecolor() buf = io.BytesIO() fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Save the figure again to check that the # colors don't bleed from the previous renderer. buf.seek(0) fig.savefig(buf, facecolor=fig.get_facecolor(), edgecolor='none') # Check the first pixel has the desired color & alpha # (approx: 0, 1.0, 0.4, 0.25) buf.seek(0) assert_array_almost_equal(tuple(imread(buf)[0, 0]), (0.0, 1.0, 0.4, 0.250), decimal=3)