本文整理汇总了Python中matplotlib.image.imread函数的典型用法代码示例。如果您正苦于以下问题:Python imread函数的具体用法?Python imread怎么用?Python imread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了imread函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: colour_back_projection_exercise
def colour_back_projection_exercise(bins, model):
"""
Uses colour back projection as descibed in Swain and Ballard's 1990 paper,
to locate a target image within a larger image. Coordinates of best guess.
"""
print '\n\nColour back projection exercise\n'
raw_input('Let\'s view the image to search & the "target":\n(Press enter)')
target = mpimg.imread('../images/waldo/waldo_no_bg.tiff')
image = mpimg.imread('../images/waldo/waldo_env.tiff')
plt.subplot(1,2,1)
plt.imshow(np.flipud(image))
plt.subplot(1,2,2)
plt.imshow(np.flipud(target))
plt.show()
print '\nNow let\'s carry out the back projection...'
locations, result_image = colour_backproject(target, image, bins, model)
print '\nThe most likely match location(s):'
print locations
plt.subplot(1,1,1)
plt.imshow(np.flipud(result_image))
plt.show()
menu()
开发者ID:joristork,项目名称:beeldbewerken,代码行数:26,代码来源:beeld_3rd_assignment.py
示例2: __init__
def __init__(self, dpi=101, x=5, y=5, image=False, imagelocation='t.png'):
# canvas
self.dpi = dpi
self.inches = np.array([x, y])
self.dots = self.dpi * self.inches
self.iterations = 0
self.speed = -3 # pause = 2^speed
if image:
# import png
print(mpimg.imread(imagelocation).shape[0:2])
self.dots = np.array(mpimg.imread(imagelocation).shape[0:2])
self.imageIn = np.uint8(255 * mpimg.imread(imagelocation))
self.fig = plt.figure(figsize=[self.dots[1], self.dots[0]], dpi=1)
else:
# draw 2d zero matrix
self.imageIn = np.zeros(shape=self.dots, dtype=np.uint8)
self.fig = plt.figure(figsize=[self.inches[1], self.inches[0]], dpi=self.dpi)
# display array as image figure
# self.fig = plt.figure(figsize=[self.inches[1], self.inches[0]], dpi=self.dpi)
# self.fig = plt.figure(figsize=self.dots, dpi=self.dpi)
self.im = self.fig.figimage(self.imageIn)
self.cid = self.fig.canvas.mpl_connect('scroll_event', self.onscroll)
开发者ID:y2kbugger,项目名称:picderivate,代码行数:25,代码来源:controlspeed.py
示例3: make_plot_1
def make_plot_1(u):
fig = plt.figure(figsize=(15,10), dpi=1000)
fig.clf()
gs = gridspec.GridSpec(2,3)
padd = 0
hpadd = 0
gs.update(left=padd, right=1-padd, top=1-hpadd, bottom=hpadd, wspace=padd, hspace=-0.3)
im = img.imread("images/poster_samplest%.2f.png"%u)
ax = fig.add_subplot(gs[0,0])
ax.imshow(im)
plt.axis('off')
im = img.imread("images/poster_samples%.2f.png"%u)
ax = fig.add_subplot(gs[1,0])
ax.imshow(im)
plt.axis('off')
im = img.imread("images/poster_rates%.2f.png"%u)
ax = fig.add_subplot(gs[1,1])
ax.imshow(im)
plt.axis('off')
im = img.imread("images/tr2trspki%.2f.png"%u)
ax = fig.add_subplot(gs[0,2])
ax.imshow(im)
# ax.set_title("Integration")
plt.axis('off')
im = img.imread("images/tr2trspkp%.2f.png"%u)
ax = fig.add_subplot(gs[1,2])
ax.imshow(im)
# ax.set_title("Poisson")
plt.axis('off')
fig.savefig("images/poster_1_%.2f.png"%u, transparent=True, frameon=False)
开发者ID:zsomko,项目名称:visualcortex,代码行数:31,代码来源:poster.py
示例4: plot_greyscale_images
def plot_greyscale_images(pngimage):
fig = plt.figure()
ax0 = fig.add_subplot(3, 2, 3)
ax1 = fig.add_subplot(3, 2, 2)
ax2 = fig.add_subplot(3, 2, 4)
ax3 = fig.add_subplot(3, 2, 6)
ax0.imshow(mpimg.imread(pngimage))
ax0.set_xticklabels([])
ax0.set_yticklabels([])
ax0.set_title('Orignal')
ax1.imshow(lightness(mpimg.imread(pngimage)), cmap='binary')
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.set_title('Lightness')
ax2.imshow(average(mpimg.imread(pngimage)), cmap='binary')
ax2.set_xticklabels([])
ax2.set_yticklabels([])
ax2.set_title('Average')
ax3.imshow(luminosity(mpimg.imread(pngimage)), cmap='binary')
ax3.set_xticklabels([])
ax3.set_yticklabels([])
ax3.set_title('Luminosity')
fig.suptitle('RGB image and three greyscale methods')
# fig.subplots_adjust(hspace=.5)
plt.savefig('BLAC_hw6_TLRH_6126561_greyscale.pdf')
开发者ID:tlrh314,项目名称:MasterAstronomyAndAstrophysics,代码行数:32,代码来源:BLAC_ex6_Friday_6126561.py
示例5: stock_img
def stock_img(self, img_name):
# XXX Turn into a dictionary (inside the method)?
if img_name == 'bluemarble':
source_proj = ccrs.PlateCarree()
fname = '/data/local/dataZoo/cartography/raster/blue_marble_720_360.png'
# fname = '/data/local/dataZoo/cartography/raster/blue_marble_2000_1000.jpg'
img_origin = 'lower'
img = imread(fname)
img = img[::-1]
return self.imshow(img, origin=img_origin, transform=source_proj, extent=[-180, 180, -90, 90])
elif img_name == 'bm_high':
source_proj = ccrs.PlateCarree()
fname = '/data/local/dataZoo/cartography/raster/blue_marble_2000_1000.jpg'
img_origin = 'lower'
img = imread(fname)
return self.imshow(img, origin=img_origin, transform=source_proj, extent=[-180, 180, -90, 90])
elif img_name == 'ne_shaded':
source_proj = ccrs.PlateCarree()
fname = '/data/local/dataZoo/cartography/raster/NE1_50M_SR_W/NE1_50M_SR_W_720_360.png'
img_origin = 'lower'
img = imread(fname)
img = img[::-1]
return self.imshow(img, origin=img_origin, transform=source_proj, extent=[-180, 180, -90, 90])
else:
raise ValueError('Unknown stock image.')
开发者ID:dmcdougall,项目名称:cartopy,代码行数:25,代码来源:geoaxes.py
示例6: plot_superimposed_heatmap
def plot_superimposed_heatmap(self, maptype=u'cancellation'):
"""Plots a heatmap superimposed on the task image"""
# draw heatmap if this has not been done yet
if not u'%salphaheatmap' % maptype in self.files.keys():
self.plot_heatmap(maptype=maptype)
# create a new figure
fig = pyplot.figure(figsize=(self.dispsize[0]/self.dpi, self.dispsize[1]/self.dpi), dpi=self.dpi, frameon=False)
ax = pyplot.Axes(fig, [0,0,1,1])
ax.set_axis_off()
fig.add_axes(ax)
# load images
taskimg = image.imread(self.files[u'task'])
heatmap = image.imread(self.files[u'%salphaheatmap' % maptype])
# resize task image
taskimg = numpy.resize(taskimg, (numpy.size(heatmap,axis=0),numpy.size(heatmap,axis=1)))
# draw task
ax.imshow(self.taskimg, origin=u'upper', alpha=1)
# superimpose heatmap
ax.imshow(heatmap, alpha=0.5)
# save figure
self.files[u'%staskheatmap' % maptype] = os.path.join(self.outdir, u'%s_heatmap_superimposed.png' % maptype)
fig.savefig(self.files[u'%staskheatmap' % maptype])
开发者ID:esdalmaijer,项目名称:CancellationTools,代码行数:25,代码来源:libanalysis.py
示例7: plot_gaussian_blur
def plot_gaussian_blur(pngimage):
red = mpimg.imread(pngimage)[:, :, 0]
green = mpimg.imread(pngimage)[:, :, 1]
blue = mpimg.imread(pngimage)[:, :, 2]
fig = plt.figure()
ax0 = fig.add_subplot(2, 1, 1)
ax1 = fig.add_subplot(2, 1, 2)
ax0.imshow(mpimg.imread(pngimage))
ax0.set_xticklabels([])
ax0.set_yticklabels([])
ax0.set_title('Original')
# gaussian_blur is in a different file, as requested.
radius, sigma = 7, 0.84089642
blurred_img = gaussian_blur(red, green, blue, radius, sigma)
print type(blurred_img), blurred_img.dtype, blurred_img.shape
ax1.imshow(blurred_img)
ax1.set_xticklabels([])
ax1.set_yticklabels([])
ax1.set_title('Gaussian Blurred with kernel size {0} and sigma {1}'
.format(radius, sigma))
fig.suptitle('Gaussian blur')
plt.savefig('BLAC_hw6_TLRH_6126561_gaussian_blur.pdf')
开发者ID:tlrh314,项目名称:MasterAstronomyAndAstrophysics,代码行数:26,代码来源:BLAC_ex6_Friday_6126561.py
示例8: updateAutoRun
def updateAutoRun(self, index):
i = self.currentIndex.get()
if index ==0:
# read current image
_tmpImage = mpimg.imread(os.path.join(self.imageFolder.get(),self.imageNames[i]))
# update coordinates
tmp_xC, tmp_yC = self.ROILocationData
# use same algorithm as manual to get fluorescence
self.AutoFluorescenceDetector(_tmpImage, tmp_xC, tmp_yC, i)
else:
# read current image
_tmpImage = mpimg.imread(os.path.join(self.imageFolder.get(),self.imageNames[i]))
# update coordinates
tmp_xC, tmp_yC = self.data[3][i-1]+(self.data[3][i-1]-self.data[3][i-2])*0.2, self.data[4][i-1]++(self.data[4][i-1]-self.data[4][i-2])*0.25
self.AutoFluorescenceDetector(_tmpImage, tmp_xC, tmp_yC, i)
self.drawDataLine()
self.updateMain()
self.drawRect()
self.drawData()
if len(self.ROI) > 0:
for item in self.ROI:
self.ax['Main'].lines.remove(item[0])
self.ROI = []
self.currentIndex.set(i+1)
index += 1
if self.AutoRunActive and index <= self.numOfImages-1:
root.after(2, lambda: self.updateAutoRun(index))
return
开发者ID:monikascholz,项目名称:PIA,代码行数:28,代码来源:pia.py
示例9: main
def main():
# parse command line arguments
parser = argparse.ArgumentParser(description='Colorize pictures')
parser.add_argument('greyImage', help='png image to be coloured')
parser.add_argument('markedImage', help='png image with colour hints')
parser.add_argument('output', help='png output file')
parser.add_argument('-v', '--view', help='display image', action='store_true')
args = parser.parse_args()
# Note: when reading .png, division by 255. is not required
# Note: when reading .bmp, division by 255. is required
# TODO: make this more universal, i.e., support various image formats
# read images
greyImage = mpimg.imread(args.greyImage, format='png')
markedImage = mpimg.imread(args.markedImage, format='png')
# colorize
colouredImage = colorize(greyImage, markedImage)
# save output
mpimg.imsave(args.output,colouredImage, format='png')
# display output, if requested
if args.view:
plt.imshow(colouredImage)
plt.show()
开发者ID:godfatherofpolka,项目名称:ColorizationUsingOptimizationInPython,代码行数:26,代码来源:colorizer.py
示例10: get_images
def get_images(images_directory, groundtruths_directory, num_images):
#
# DESCRIPTION
# Loads each training image and its ground truth and creates tensors [numImages, 400, 400, 3]
#
# INPUTS
# images_directory path to training images directory
# groundtruths_directory path to the groundtruth images directory
# num_images number of images to load
#
# OUTPUTS
# images, ground_truth two tensors
#
images = []
ground_truth = []
for i in num_images:
image_id = "satImage_%.3d" % i
image_filename = image_id + ".png"
image_path = images_directory + image_filename;
groundtruth_image_path = groundtruths_directory + image_filename;
if ((os.path.isfile(image_path))&(os.path.isfile(groundtruth_image_path))):
print ('Loading ' + image_filename)
loaded_image = mpimg.imread(image_path)
loaded_gt_image = mpimg.imread(groundtruth_image_path)
if ordering == "th":
loaded_image = np.rollaxis(loaded_image,2)
images.append(loaded_image)
ground_truth.append(loaded_gt_image)
else:
print ('File ' + image_path + ' does not exist')
return images, ground_truth
开发者ID:albertbuchard,项目名称:semantic-segmentation,代码行数:35,代码来源:run_FCN.py
示例11: _render
def _render(self):
"""
Render the current cursor image into the canvas.
"""
# If path to datasets folder is provided we need to exchange the path in the path to
# the image in order to be able to load the image
if self.path_datasets is not None:
path_image = self.file_list[self.cursor]
# Find the position of the "datasets" folder in the path
pos = path_image.find('/datasets/') + 1
if pos >= 0:
path_image = os.path.join(self.path_datasets, path_image[pos:])
img = mpimg.imread(path_image)
else:
img = mpimg.imread(self.file_list[self.cursor])
# Render
self.ax.cla()
self.ax.imshow(img)
self.ax.set_xlim([0, img.shape[1]])
self.ax.set_ylim([img.shape[0], 0])
if self.iml_gt is not None:
self._render_bounding_boxes(self.iml_gt, self.gt_mapping, gt=True)
self._render_bounding_boxes(self.iml_detections, self.detections_mapping)
plt.title('[' + str(self.cursor) + '/' + str(len(self.file_list)) + '] ' + self.file_list[self.cursor] + ' (((' + str(self.confidence) + ')))')
plt.axis('off')
self.fig.canvas.draw()
plt.subplots_adjust(left=0.0, right=1.0, top=1.0, bottom=0.0)
开发者ID:billow06,项目名称:master_thesis_code,代码行数:31,代码来源:show_bbtxt_detections.py
示例12: clean_directory
def clean_directory(path):
for img_file in tqdm(glob(path)):
try:
mpimg.imread(img_file)
except Exception as e:
print('removing ' + os.path.join(path, img_file))
os.remove(os.path.join(path, img_file))
开发者ID:ashishpatel26,项目名称:w-net,代码行数:7,代码来源:data_loader.py
示例13: test_devectorize_axes
def test_devectorize_axes():
np.random.seed(0)
x, y = np.random.random((2, 1000))
# save vectorized version
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y)
sio = StringIO()
fig.savefig(sio)
sio.reset()
im1 = image.imread(sio)
plt.close()
# save devectorized version
fig = plt.figure()
ax = fig.add_subplot(111)
ax.scatter(x, y)
devectorize_axes(ax, dpi=200)
sio = StringIO()
fig.savefig(sio)
sio.reset()
im2 = image.imread(sio)
plt.close()
assert_(im1.shape == im2.shape)
assert_((im1 != im2).sum() < 0.1 * im1.size)
开发者ID:CKrawczyk,项目名称:astroML,代码行数:28,代码来源:test_devectorize.py
示例14: createImages
def createImages(prefix1,prefix2,prefix3,outDescription):
suffix = '.png'
length = len(utils.benchmarks)
images = []
for i in range(length): #range(length):
dataset = utils.benchmarks[i]
img1 = mpimg.imread(prefix1+dataset+suffix)
img2 = mpimg.imread(prefix2+dataset+suffix)
img3 = mpimg.imread(prefix3+dataset+suffix)
fig = plt.figure(i)
plt.subplot(1, 3,1)
imgplot1 = plt.imshow(img1)
plt.axis('off')
#plt.subplot(1, 2,2*i+2)
plt.subplot(1, 3,2)
imgplot2 = plt.imshow(img2)
plt.axis('off')
plt.subplot(1, 3,3)
imgplot2 = plt.imshow(img3)
plt.axis('off')
fig.savefig(outDescription + dataset + '.png',dpi=100)
#plt.show()
plt.close('all')
开发者ID:sharwick,项目名称:UICCS565_Project,代码行数:30,代码来源:alignImages.py
示例15: rotate_training
def rotate_training():
## Saves rotated versions of each image in the training set
niter = 10
k=5
for i in np.linspace(1,100,100):
truth = mpimg.imread('training/groundtruth/satImage_'+ '%.3d' % i +'.png')
image = mpimg.imread('training/images/satImage_'+ '%.3d' % i +'.png')
imgs = mk_rotations(image)
truths = mk_rotations(truth)
count =0
for im in imgs:
im = format_image(im)
Image.fromarray(im).save('training_big/Images/satImage_'+ '%.3d' % i +'_rota'+str(np.int(count))+'.png')
count+=1
count =0
for im in imgs:
im = format_image(im)
Image.fromarray(im).save('training_big/Truth/satImage_'+ '%.3d' % i +'_rota'+str(np.int(count))+'.png')
count+=1
print('Writing image ',i)
return 0
开发者ID:albertbuchard,项目名称:semantic-segmentation,代码行数:29,代码来源:Training_run.py
示例16: diff_viewer
def diff_viewer(expected_fname, result_fname, diff_fname):
plt.figure(figsize=(16, 16))
plt.suptitle(os.path.basename(expected_fname))
ax = plt.subplot(221)
ax.imshow(mimg.imread(expected_fname))
ax = plt.subplot(222, sharex=ax, sharey=ax)
ax.imshow(mimg.imread(result_fname))
ax = plt.subplot(223, sharex=ax, sharey=ax)
ax.imshow(mimg.imread(diff_fname))
def accept(event):
# removes the expected result, and move the most recent result in
print('ACCEPTED NEW FILE: %s' % (os.path.basename(expected_fname), ))
os.remove(expected_fname)
shutil.copy2(result_fname, expected_fname)
os.remove(diff_fname)
plt.close()
def reject(event):
print('REJECTED: %s' % (os.path.basename(expected_fname), ))
plt.close()
ax_accept = plt.axes([0.7, 0.05, 0.1, 0.075])
ax_reject = plt.axes([0.81, 0.05, 0.1, 0.075])
bnext = mwidget.Button(ax_accept, 'Accept change')
bnext.on_clicked(accept)
bprev = mwidget.Button(ax_reject, 'Reject')
bprev.on_clicked(reject)
plt.show()
开发者ID:Jozhogg,项目名称:iris,代码行数:30,代码来源:idiff.py
示例17: compare_entropy
def compare_entropy(name_img1,name_img2,method="rmq"):
'''Compare two images by the Kullback-Leibler divergence
Parameters
----------
name_img1 : string
filename of image 1 (png format)
name_img2 : string
filename of image 2 (png format)
Returns
-------
S : float
Kullback-Leibler divergence S = sum(pk * log(pk / qk), axis=0)
Note
----
See http://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.entropy.html
'''
img1 = mpimg.imread(name_img1)
img2 = mpimg.imread(name_img2)
fimg1 = img1.flatten()
fimg2 = img2.flatten()
if method == "KL-div":
eps = 0.0001
S = stats.entropy(fimg2+eps,fimg1+eps)
S = numpy.log10(S)
elif method == "rmq":
fdiff=fimg1-fimg2
fdiff_sqr = fdiff**4
S = (fdiff_sqr.sum())**(old_div(1.,4))
return S,fimg1, fimg2
开发者ID:NuGrid,项目名称:NuGridPy,代码行数:34,代码来源:compare_image_entropy.py
示例18: two_brains_two_graphs
def two_brains_two_graphs():
brain_ax = plt.subplot(gs[:-g2, :g3])
brain_ax.set_aspect('equal')
brain_ax.get_xaxis().set_visible(False)
brain_ax.get_yaxis().set_visible(False)
image = mpimg.imread(images[0])
im = brain_ax.imshow(image, animated=True)#, cmap='gray',interpolation='nearest')
brain_ax2 = plt.subplot(gs[:-g2, g3:-1])
brain_ax2.set_aspect('equal')
brain_ax2.get_xaxis().set_visible(False)
brain_ax2.get_yaxis().set_visible(False)
image2 = mpimg.imread(images2[0])
im2 = brain_ax2.imshow(image2, animated=True)#, cmap='gray',interpolation='nearest')
graph1_ax = plt.subplot(gs[-g2:, :])
graph2_ax = graph1_ax.twinx()
if cb_data_type != '':
ax_cb = plt.subplot(gs[:-g2, -1])
else:
ax_cb = None
plt.tight_layout()
resize_and_move_ax(brain_ax, dx=0.04)
resize_and_move_ax(brain_ax2, dx=-0.00)
if cb_data_type != '':
resize_and_move_ax(ax_cb, ddw=0.5, ddh=0.8, dx=-0.01, dy=0.06)
for graph_ax in [graph1_ax, graph2_ax]:
resize_and_move_ax(graph_ax, dx=0.04, dy=0.03, ddw=0.89)
return ax_cb, im, im2, graph1_ax, graph2_ax
开发者ID:ofek-schechner,项目名称:mmvt,代码行数:31,代码来源:make_movie.py
示例19: input_image_setup
def input_image_setup(img_name, img2_name):
''' Nimmt ein Bild als input, erstellt eine "Regel-Karte". Bei der Bild-
erstellung bedenken: Rot = Gitter, Gruen = Verzweigt, Blau = Radial, wobei ein schwarzer
Pixel ein Zentrum definiert. '''
#TODO: Document
import matplotlib.image as mpimg
import matplotlib.pyplot as plt
import procedural_city_generation
import os
#TODO:translate
img = mpimg.imread(img_name)
img2 = mpimg.imread(img2_name)
import matplotlib.pyplot as plt
path=os.path.dirname(procedural_city_generation.__file__)
print path
plt.imsave(path+"/temp/diffused.png",img2,cmap='gray')
with open(path+"/temp/isdiffused.txt",'w') as f:
f.write("False")
img*=255
img2*=255
return img, img2
开发者ID:CodeMason,项目名称:procedural_city_generation,代码行数:25,代码来源:input_image_setup.py
示例20: imgHibrida
def imgHibrida():
raiz = os.getcwd()
filtro = gaussiana(9)
alinear(Image.open(raiz + "\human.png"), Image.open(raiz + "\cat.png"))
gato = mpimg.imread(raiz + "\cat.png")
print gato.shape
humano = mpimg.imread(raiz + "\humanAlign.png")
gatoConv = lowFilter(gato, filtro)
humanoConv = lowFilter(humano, filtro)
gatoHighConv = highFilter(gato, gatoConv)
plt.show()
plt.imshow(gatoHighConv)
plt.colorbar()
plt.title("Gat(Convolution with hp)")
plt.show()
plt.imshow(humanoConv)
plt.colorbar()
plt.title("Human(Convolution with lp)")
finalImage = gatoHighConv + humanoConv
normalizar(finalImage)
plt.show()
plt.imshow(finalImage)
plt.colorbar()
plt.title("Hybrid Image")
mpimg.imsave("HybridImage1.png", finalImage)
开发者ID:Yue93,项目名称:PID,代码行数:29,代码来源:practica1.py
注:本文中的matplotlib.image.imread函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论