本文整理汇总了Python中matplotlib._png.read_png函数的典型用法代码示例。如果您正苦于以下问题:Python read_png函数的具体用法?Python read_png怎么用?Python read_png使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了read_png函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: save_diff_image
def save_diff_image(expected, actual, output):
expectedImage = _png.read_png(expected)
actualImage = _png.read_png(actual)
actualImage, expectedImage = crop_to_same(
actual, actualImage, expected, expectedImage)
expectedImage = np.array(expectedImage).astype(np.float)
actualImage = np.array(actualImage).astype(np.float)
assert expectedImage.ndim == actualImage.ndim
assert expectedImage.shape == actualImage.shape
absDiffImage = abs(expectedImage - actualImage)
# expand differences in luminance domain
absDiffImage *= 255 * 10
save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8)
height, width, depth = save_image_np.shape
# The PDF renderer doesn't produce an alpha channel, but the
# matplotlib PNG writer requires one, so expand the array
if depth == 3:
with_alpha = np.empty((height, width, 4), dtype=np.uint8)
with_alpha[:, :, 0:3] = save_image_np
save_image_np = with_alpha
# Hard-code the alpha channel to fully solid
save_image_np[:, :, 3] = 255
_png.write_png(save_image_np.tostring(), width, height, output)
开发者ID:Creence,项目名称:matplotlib,代码行数:27,代码来源:compare.py
示例2: __init__
def __init__(self, color, figName,
path= None):
if path == None:
try:
path1= wx.GetApp().installDir
except:
path1= sys.argv[0]
path1= path1.decode( sys.getfilesystemencoding())
IMAGESPATH= os.path.join( path1, 'nicePlot','images')
self.original_image = read_png( str( os.path.relpath(
os.path.join(IMAGESPATH, "barplot", figName + '.png'))))
else:
self.original_image = read_png( str(os.path.relpath(
os.path.join(path, figName + '.png'))))
self.cut_location = 70
self.b_and_h= self.original_image[:,:,2]
self.color= self.original_image[:,:,2] - self.original_image[:,:,0]
self.alpha= self.original_image[:,:,3]
self.nx= self.original_image.shape[1]
rgb= matplotlib.colors.colorConverter.to_rgb(color)
im= np.empty(self.original_image.shape,
self.original_image.dtype)
im[:,:,:3] = self.b_and_h[:,:,np.newaxis]
im[:,:,:3] -= self.color[:,:,np.newaxis]*(1.-np.array(rgb))
im[:,:,3] = self.alpha
self.im = im
开发者ID:debbiespiegel,项目名称:salstat-statistics-package-2,代码行数:30,代码来源:graficaRibon.py
示例3: save_diff_image
def save_diff_image(expected, actual, output):
expectedImage = _png.read_png(expected)
actualImage = _png.read_png(actual)
actualImage, expectedImage = crop_to_same(
actual, actualImage, expected, expectedImage)
expectedImage = np.array(expectedImage).astype(float)
actualImage = np.array(actualImage).astype(float)
if expectedImage.shape != actualImage.shape:
raise ImageComparisonFailure(
"Image sizes do not match expected size: {0} "
"actual size {1}".format(expectedImage.shape, actualImage.shape))
absDiffImage = np.abs(expectedImage - actualImage)
# expand differences in luminance domain
absDiffImage *= 255 * 10
save_image_np = np.clip(absDiffImage, 0, 255).astype(np.uint8)
height, width, depth = save_image_np.shape
# The PDF renderer doesn't produce an alpha channel, but the
# matplotlib PNG writer requires one, so expand the array
if depth == 3:
with_alpha = np.empty((height, width, 4), dtype=np.uint8)
with_alpha[:, :, 0:3] = save_image_np
save_image_np = with_alpha
# Hard-code the alpha channel to fully solid
save_image_np[:, :, 3] = 255
_png.write_png(save_image_np, output)
开发者ID:Eric89GXL,项目名称:matplotlib,代码行数:29,代码来源:compare.py
示例4: createMovie
def createMovie(self):
'''
open all movie-template-*.png's and create a movie out of it
'''
print "createMovie(): writing image data"
frameSizeImage = read_png(''.join([self.templateMovDataDirectory,'/.screenShot',str(0),'.png']))
frameSize = (np.shape(frameSizeImage)[1],np.shape(frameSizeImage)[0])
try: FFMpegWriter = animation.writers['mencoder']
except: print "ERROR: Visualisation3D.createMovie(): mencoder libary is not installed, could not create movie!"; return
try:
fileName = ''.join([self.movieSaveDirectory,'/',self.networkName,'_',str(self.movieNumber),self.movieFileType])
imageName = ''.join(['mf://',self.templateMovDataDirectory,'/.screenShot%d.png'])
imageType = ''.join(['type=png:w=',str(frameSize[0]),':h=',str(frameSize[1]),':fps=24'])
command = ('mencoder',
imageName,
'-mf',
imageType,
'-ovc',
'lavc',
'-lavcopts',
'vcodec=mpeg4',
'-oac',
'copy',
'-o',
fileName)
os.spawnvp(os.P_WAIT, 'mencoder', command)
self.movieNumber = self.movieNumber+1
print "createMovie(): created movie sucessfull"
except:
print "ERROR: Visualisation3D.createMovie(): mencoder libary is not installed, could not create movie!"; return
开发者ID:Biomechanics-NTNU,项目名称:STARFiSh_v0.3,代码行数:33,代码来源:class3dVisualisation.py
示例5: paste_image
def paste_image(filename):
# annotate plot and paste image
fig, ax = plt.subplots()
xy = (0.5, 0.7)
ax.plot(xy[0], xy[1], ".r")
fn = get_sample_data(filename, asfileobj=False)
arr_lena = read_png(fn)
imagebox = OffsetImage(arr_lena, zoom=0.2)
ab = AnnotationBbox(imagebox, xy,
xybox=(120., -80.),
xycoords='data',
boxcoords="offset points",
pad=0.5,
arrowprops=dict(arrowstyle="->", connectionstyle="angle,angleA=0,angleB=90,rad=3")
)
ax.add_artist(ab)
ax.set_xlim(0, 1)
ax.set_ylim(0, 1)
plt.draw()
plt.show()
开发者ID:PierreExeter,项目名称:plot2d,代码行数:27,代码来源:function_lib.py
示例6: __init__
def __init__(self, ax, n):
self.ax = ax
dir=os.path.abspath(os.path.dirname(sys.argv[0]))
ax.axis([0,1,0,1])
ax.axes.get_xaxis().set_visible(False)
ax.axes.get_yaxis().set_visible(False)
ax.set_frame_on=True
ax.plot( [ 0.1, 0.2], [0.96, 0.96], color='blue', linewidth=2 )
ax.plot( [ 0.1, 0.2], [0.91, 0.91], color='green', linewidth=2 )
ax.plot( [ 0.1, 0.2], [0.86, 0.86], color='red', linewidth=1 )
self.text1 = ax.text( 0.3, self.ypos(2), '%d' % n )
fn = get_sample_data("%s/coolr-logo-poweredby-48.png" % dir, asfileobj=False)
arr = read_png(fn)
imagebox = OffsetImage(arr, zoom=0.4)
ab = AnnotationBbox(imagebox, (0, 0),
xybox=(.75, .12),
xycoords='data',
boxcoords="axes fraction",
pad=0.5)
ax.add_artist(ab)
开发者ID:coolr-hpc,项目名称:pycoolr,代码行数:25,代码来源:clr_matplot_graphs.py
示例7: rna_draw
def rna_draw(seq, struct, name, out_type = 'svg'):
lines = '{0}\n{1}\n'.format(seq,struct)
if out_type == 'png':
outfile = cfg.dataPath('rnafold/{0}.png'.format(name))
rprc = spc.Popen('RNAplot -o svg; convert rna.svg {0}'.format(outfile), shell = True,
stdin = spc.PIPE, stdout = spc.PIPE)
out = rprc.communicate(input = lines)[0].splitlines()
from matplotlib._png import read_png
image = read_png(outfile)
elif out_type== 'svg':
outfile = cfg.dataPath('rnafold/{0}.svg'.format(name))
tempdir = 'tmp_{0}'.format(name);
rprc = spc.Popen('mkdir {1}; cd {1}; RNAplot -o svg; mv rna.svg {0}; cd ..; rm -r {1};'.format(outfile, tempdir), shell = True,
stdin = spc.PIPE, stdout = spc.PIPE)
out = rprc.communicate(input = lines)[0].splitlines()
struct_svg = open(outfile).read()
data = xparse.parse(struct_svg)
arr = svg.get_polys(data)[0]
else:
raise Exception()
return arr
开发者ID:bh0085,项目名称:projects,代码行数:29,代码来源:utils.py
示例8: main
def main():
# load sample data
data = np.loadtxt("distmat799.txt", delimiter=",")
dists = data / np.amax(data)
# load images
img_files = [img for img in os.listdir("799_patch") if re.search(r"\.png", img)]
# mds
mds = MDS(n_components=2, dissimilarity="precomputed")
results = mds.fit(dists)
# plot
fig, ax = plt.subplots()
for i, img_file in enumerate(img_files):
img_file = os.path.join("799_patch", img_file)
img = read_png(img_file)
imagebox = OffsetImage(img, zoom=2.0)
coords = results.embedding_[i, :]
xy = tuple(coords)
ab = AnnotationBbox(imagebox, xy)
ax.add_artist(ab)
ax.set_xlim(-1.0, 1.0)
ax.set_ylim(-1.0, 1.0)
plt.show()
开发者ID:vkarthi46,项目名称:ml-algorithms-simple,代码行数:25,代码来源:mds_sklearn_sample2.py
示例9: getPic
def getPic(pic):
for filename in os.listdir("./stimuli/"):
if filename.startswith(pic):
print filename
picture = read_png('./stimuli/'+str(filename))
return picture
开发者ID:sagar87,项目名称:Exploring-Neural-Data-Final-Project,代码行数:8,代码来源:final.py
示例10: get_grey
def get_grey(self, tex, fontsize=None, dpi=None):
"""returns the alpha channel"""
key = tex, self.get_font_config(), fontsize, dpi
alpha = self.grey_arrayd.get(key)
if alpha is None:
pngfile = self.make_png(tex, fontsize, dpi)
X = read_png(os.path.join(self.texcache, pngfile))
self.grey_arrayd[key] = alpha = X[:, :, -1]
return alpha
开发者ID:Eric89GXL,项目名称:matplotlib,代码行数:9,代码来源:texmanager.py
示例11: add_logo_on_map
def add_logo_on_map(imagepath, ax, position, zoom, zorder):
logo2plot = read_png(imagepath)
imagebox = OffsetImage(logo2plot, zoom=zoom)
# coordinates to position this image
ab = AnnotationBbox(imagebox, position, xybox=(0.0, 0.0), xycoords="data", pad=0.0, boxcoords="offset points")
ab.zorder = zorder
ax.add_artist(ab)
开发者ID:ctroupin,项目名称:SOCIB_plots,代码行数:9,代码来源:plot_turtle_altimetry_visible.py
示例12: get_grey
def get_grey(self, tex, fontsize=None, dpi=None):
"""Return the alpha channel."""
from matplotlib import _png
key = tex, self.get_font_config(), fontsize, dpi
alpha = self.grey_arrayd.get(key)
if alpha is None:
pngfile = self.make_png(tex, fontsize, dpi)
X = _png.read_png(os.path.join(self.texcache, pngfile))
self.grey_arrayd[key] = alpha = X[:, :, -1]
return alpha
开发者ID:ianthomas23,项目名称:matplotlib,代码行数:10,代码来源:texmanager.py
示例13: logo_box
def logo_box(self):
logo_offset_image = OffsetImage(read_png(get_sample_data(logo_location, asfileobj=False)), zoom=0.25, resample=1, dpi_cor=1)
text_box = TextArea(logo_text, textprops=dict(color='#444444', fontsize=50, weight='bold'))
logo_and_text_box = HPacker(children=[logo_offset_image, text_box], align="center", pad=0, sep=25)
anchored_box = AnchoredOffsetbox(loc=2, child=logo_and_text_box, pad=0.8, frameon=False, borderpad=0.)
return anchored_box
开发者ID:tripatheea,项目名称:MODAnalyzer,代码行数:10,代码来源:MODPlot.py
示例14: save_diff_image
def save_diff_image(expected, actual, output):
'''
Parameters
----------
expected : str
File path of expected image.
actual : str
File path of actual image.
output : str
File path to save difference image to.
'''
# Drop alpha channels, similarly to compare_images.
from matplotlib import _png
expected_image = _png.read_png(expected)[..., :3]
actual_image = _png.read_png(actual)[..., :3]
actual_image, expected_image = crop_to_same(
actual, actual_image, expected, expected_image)
expected_image = np.array(expected_image).astype(float)
actual_image = np.array(actual_image).astype(float)
if expected_image.shape != actual_image.shape:
raise ImageComparisonFailure(
"Image sizes do not match expected size: {} "
"actual size {}".format(expected_image.shape, actual_image.shape))
abs_diff_image = np.abs(expected_image - actual_image)
# expand differences in luminance domain
abs_diff_image *= 255 * 10
save_image_np = np.clip(abs_diff_image, 0, 255).astype(np.uint8)
height, width, depth = save_image_np.shape
# The PDF renderer doesn't produce an alpha channel, but the
# matplotlib PNG writer requires one, so expand the array
if depth == 3:
with_alpha = np.empty((height, width, 4), dtype=np.uint8)
with_alpha[:, :, 0:3] = save_image_np
save_image_np = with_alpha
# Hard-code the alpha channel to fully solid
save_image_np[:, :, 3] = 255
_png.write_png(save_image_np, output)
开发者ID:HubertHolin,项目名称:matplotlib,代码行数:41,代码来源:compare.py
示例15: initUI
def initUI(self):
# layout
vbox = QtGui.QVBoxLayout()
self.setLayout(vbox)
# set up canvas
self.figure = plt.figure(figsize=(10,5),facecolor='None',edgecolor='None')
self.canvas = FigureCanvas(self.figure)
vbox.addWidget(self.canvas)
# image parameters, axes refer to setup axes
self.x_max = 2
self.y_max = 4
self.mologram = read_png('./images/mologram.png')
self.mologram_turned = read_png('./images/mologram_turned.png')
# initial display
self.initDisplay()
cid = self.figure.canvas.mpl_connect('button_press_event', self.onclick)
开发者ID:afrutig,项目名称:Moloreader_high_end,代码行数:22,代码来源:MologramLineRow.py
示例16: get_weather_icons
def get_weather_icons(ww, time):
from matplotlib._png import read_png
"""
Get the path to a png given the weather representation
"""
weather = [WMO_GLYPH_LOOKUP_PNG[w.astype(int).astype(str)] for w in ww.values]
weather_icons=[]
for date, weath in zip(time, weather):
if date.hour >= 6 and date.hour <= 18:
add_string='d'
elif date.hour >=0 and date.hour < 6:
add_string='n'
elif date.hour >18 and date.hour < 24:
add_string='n'
pngfile=folder_glyph+'%s.png' % (weath+add_string)
if os.path.isfile(pngfile):
weather_icons.append(read_png(pngfile))
else:
pngfile=folder_glyph+'%s.png' % weath
weather_icons.append(read_png(pngfile))
return(weather_icons)
开发者ID:guidocioni,项目名称:icon_globe,代码行数:23,代码来源:utils.py
示例17: put_team_logo_annotationbbox
def put_team_logo_annotationbbox(filename,xy,xybox=(40., +80.)):
fn = get_sample_data(filename, asfileobj=False)
arr_lena = read_png(fn)
imagebox = OffsetImage(arr_lena, zoom=0.02 )
# xy = [4, 75]
ab = AnnotationBbox(imagebox, xy,
xybox=xybox,
xycoords='data',
boxcoords="offset points",
pad=0.0,frameon=False,
arrowprops=dict(arrowstyle="->",alpha=.75,linestyle='dashed',
connectionstyle="angle,angleA=50,angleB=90,rad=3")
)
ax.add_artist(ab)
开发者ID:carlosfugazi,项目名称:LeagueAnalysis,代码行数:15,代码来源:laliga_analysis.py
示例18: get_grey
def get_grey(self, tex, fontsize=None, dpi=None):
"""returns the alpha channel"""
key = tex, self.get_font_config(), fontsize, dpi
alpha = self.grey_arrayd.get(key)
if alpha is None:
pngfile = self.make_png(tex, fontsize, dpi)
X = read_png(os.path.join(self.texcache, pngfile))
if rcParams['text.dvipnghack'] is not None:
hack = rcParams['text.dvipnghack']
else:
if TexManager._dvipng_hack_alpha is None:
TexManager._dvipng_hack_alpha = dvipng_hack_alpha()
hack = TexManager._dvipng_hack_alpha
if hack:
# hack the alpha channel
# dvipng assumed a constant background, whereas we want to
# overlay these rasters with antialiasing over arbitrary
# backgrounds that may have other figure elements under them.
# When you set dvipng -bg Transparent, it actually makes the
# alpha channel 1 and does the background compositing and
# antialiasing itself and puts the blended data in the rgb
# channels. So what we do is extract the alpha information
# from the red channel, which is a blend of the default dvipng
# background (white) and foreground (black). So the amount of
# red (or green or blue for that matter since white and black
# blend to a grayscale) is the alpha intensity. Once we
# extract the correct alpha information, we assign it to the
# alpha channel properly and let the users pick their rgb. In
# this way, we can overlay tex strings on arbitrary
# backgrounds with antialiasing
#
# red = alpha*red_foreground + (1-alpha)*red_background
#
# Since the foreground is black (0) and the background is
# white (1) this reduces to red = 1-alpha or alpha = 1-red
#alpha = npy.sqrt(1-X[:,:,0]) # should this be sqrt here?
alpha = 1-X[:,:,0]
else:
alpha = X[:,:,-1]
self.grey_arrayd[key] = alpha
return alpha
开发者ID:AlexSzatmary,项目名称:matplotlib,代码行数:46,代码来源:texmanager.py
示例19: AddLogo
def AddLogo(logo_name, ax, zoom=1.2):
"""Read logo from PNG file and add it to axes."""
logo_data = read_png(logo_name)
fig_dpi = ax.get_figure().dpi
fig_size = ax.get_figure().get_size_inches()
# NOTE: This scaling is kinda ad hoc...
zoom_factor = .1 / 1.2 * fig_dpi * fig_size[0] / np.shape(logo_data)[0]
zoom_factor *= zoom
logo_box = OffsetImage(logo_data, zoom=zoom_factor)
ann_box = AnnotationBbox(logo_box, [0., 1.],
xybox=(2., -3.),
xycoords="axes fraction",
boxcoords="offset points",
box_alignment=(0., 1.),
pad=0., frameon=False)
ax.add_artist(ann_box)
开发者ID:Andrej-CMS,项目名称:cmssw,代码行数:17,代码来源:public_plots_tools.py
示例20: add_cut_glyph
def add_cut_glyph(parent_fig=None,parent_axes=None,pos=(0.8,0.8),size=(.1),cut='NS',pol='NS'):
#transformation stuff to put the little axis in the desired subplot
if parent_fig is None:
parent_fig = gcf()
if parent_axes is None:
parent_axes = gca()
axtrans = parent_axes.transAxes
figtrans = parent_fig.transFigure.inverted()
figpos = figtrans.transform(axtrans.transform(pos)) #get the desired position in figure units
pos = tuple(figpos)+ (size,size) #form up the extent box tuple
ax = parent_fig.add_axes(pos,'square')
ax.set_yticks([])
ax.set_xticks([])
ax.set_frame_on(False)
myglyph = '../figures/cut_glyphs_cut{cut}_rx{pol}_tx{pol}.png'.format(cut=cut,pol=pol)
glyph = read_png(myglyph)
ax.imshow(glyph,interpolation='none')
return
开发者ID:dannyjacobs,项目名称:ECHO,代码行数:18,代码来源:plot_utils.py
注:本文中的matplotlib._png.read_png函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论