本文整理汇总了Python中matplotlib.pyplot.imread函数的典型用法代码示例。如果您正苦于以下问题:Python imread函数的具体用法?Python imread怎么用?Python imread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了imread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: imread
def imread(self, xy_range=None,
f_data='daudi_PS_CD20_postwash.png',
fold='../Lymphoma_optimal_Data_20161007/'):
disp = self.disp
# fold = '../Lymphoma_optimal_Data_20161007/'
# Data = plt.imread(fold + 'daudi_PS_CD20_postwash.png')
Data = plt.imread(fold + f_data)
Ref = plt.imread(fold + 'reference_image.png')
if xy_range is not None:
# onvert a vector to four scalars
minx, maxx, miny, maxy = xy_range
Data = Data[miny:maxy, minx:maxx]
Ref = Ref[miny:maxy, minx:maxx]
bgData = np.mean(Data)
bgRef = np.mean(Ref)
NormFactor = bgRef / bgData
if disp:
print("NormFacter =", NormFactor)
subNormAmp = np.sqrt(Data / Ref * NormFactor)
if self.disp:
print(Data.shape, Ref.shape, subNormAmp.shape)
self.Data, self.Ref = Data, Ref
self.subNormAmp = subNormAmp
示例2: plotPhoto
def plotPhoto():
i = plt.imread("img1.png")
i2 = plt.imread("img2.png")
# i=np.mean(i,2)
"""Get fft and ifft"""
FFT1 = np.fft.fftshift(np.fft.fft2(i))
IFFT1 = np.real(np.fft.ifft2(np.fft.ifftshift(FFT1)))
FFT2 = np.fft.fftshift(np.fft.fft2(i2))
IFFT2 = np.real(np.fft.ifft2(np.fft.ifftshift(FFT2)))
"""plot fft and ifft """
plt.subplot(1, 2, 1)
plt.imshow(np.log(abs(FFT1)) ** 2)
plt.subplot(1, 2, 2)
plt.imshow(IFFT1)
plt.show()
plt.subplot(1, 2, 1)
plt.imshow(np.log(abs(FFT2)) ** 2)
plt.subplot(1, 2, 2)
plt.imshow(IFFT2)
plt.show()
示例3: display_bb
def display_bb(name, name2bb, lpix, rpix, ov1pix, ov2pix):
plt.clf()
try:
image_folder_name = str('_'.join(name.split('_')[:-1])) + '/'
imagename = str(driving_images_dir + image_folder_name + name + '.jpeg')
im = plt.imread(imagename)
except:
imagename = '/scail/group/deeplearning/sail-deep-gpu/brodyh/labeled_driving_images/' + name + '.jpeg'
im = plt.imread(imagename)
implot = plt.imshow(im)
plt.plot(lpix[0, :], lpix[1, :], color = 'b')
plt.plot(rpix[0, :], rpix[1, :], color = 'b')
for i in xrange(0, ov1pix.shape[1]):
plt.plot([ov1pix[0, i], ov2pix[0, i]], [ov1pix[1, i], ov2pix[1, i]], color = 'r', linestyle = '-', linewidth = 1.0)
for b in name2bb[name]['boxes']:
if get_area(b) < 20: continue
plot_box(b['xmin'], b['ymin'], b['xmax'], b['ymax'], 'g')
if b['depth'] == 0:
plt.text((b['xmin'] + b['xmax']) / 2, (b['ymax'] + b['ymin']) / 2, 'unknown', color = 'm')
else:
plt.text((b['xmin'] + b['xmax']) / 2, (b['ymax'] + b['ymin']) / 2 - 10, str(int(b['depth'])), color = 'm')
plt.axis('off')
plt.xlim([1920, 0])
plt.ylim([1280, 0])
plt.draw()
plt.pause(1.5)
示例4: site_to_array
def site_to_array(sitepath):
'''Accepts absolute path to a single w1 image file (wavelength 1).
Checks for additional channels and compiles all channels into a
single three dimensional NumPy array.
'''
path, name = os.path.split(sitepath)
w1check = re.search('w1', name)
if(w1check):
sarray = plt.imread(sitepath)
files = os.listdir(path)
w2check = name.replace('w1', 'w2')
w3check = name.replace('w1', 'w3')
w4check = name.replace('w1', 'w4')
if(w2check in files):
w2 = plt.imread(os.path.join(path, w2check))
sarray = np.dstack((sarray, w2))
if(w3check in files):
w3 = plt.imread(os.path.join(path, w3check))
sarray = np.dstack((sarray, w3))
if(w4check in files):
w4 = plt.imread(os.path.join(path, w4check))
sarray = np.dstack((sarray, w4))
return(sarray)
示例5: init_map
def init_map():
global aspect, mapImg, maskImg, burrImg, burrIndx, imgXSize, imgYSize, imgZSize, xOff
# Display Background Map
burrImg = Image.open('BurroughsIndxNoBg.png')
(imgYSize, imgXSize) = (burrImg.height, burrImg.width)
burrIndx = np.array(burrImg.convert('P'))
# Clean up partial-surface pixels
for y in range(imgYSize):
for x in range(imgXSize):
if burrIndx[y,x] not in (0, 1, 2, 3, 4, 5):
burrIndx[y,x] = 0
aspect = float(imgXSize)/float(imgYSize)
(xScale, yScale) = (imgXSize * aspect / imgXSize, 1.)
xOff = (1. - xScale)/2.
# Load Background Image
backImg = plt.imread('UHF42EdMap.png')
axes.ax.imshow(backImg, extent=[xOff, xOff+xScale, 0, yScale], alpha=1)
# Display Boroughs Index Map
axes.ax.imshow(burrImg, extent=[xOff, xOff+xScale, 0, yScale])
# Load mask map
maskImg = plt.imread('BurroughsMask.png')
示例6: test_imsave
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)
示例7: match_plot
def match_plot(plotdata, outfile):
"""Plot list of motifs with database match and p-value
"param plotdata: list of (motif, dbmotif, pval)
"""
fig_h = 2
fig_w = 7
nrows = len(plotdata)
ncols = 2
fig = plt.figure(figsize=(fig_w, nrows * fig_h))
for i, (motif, dbmotif, pval) in enumerate(plotdata):
text = "Motif: %s\nBest match: %s\np-value: %0.2e" % (motif.id, dbmotif.id, pval)
grid = ImageGrid(fig, (nrows, ncols, i * 2 + 1), nrows_ncols=(2, 1), axes_pad=0)
for j in range(2):
axes_off(grid[j])
tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
motif.to_img(tmp.name, format="PNG", height=6)
grid[0].imshow(plt.imread(tmp.name), interpolation="none")
tmp = NamedTemporaryFile(dir=mytmpdir(), suffix=".png")
dbmotif.to_img(tmp.name, format="PNG")
grid[1].imshow(plt.imread(tmp.name), interpolation="none")
ax = plt.subplot(nrows, ncols, i * 2 + 2)
axes_off(ax)
ax.text(0, 0.5, text, horizontalalignment="left", verticalalignment="center")
plt.savefig(outfile, dpi=300, bbox_inches="tight")
plt.close(fig)
示例8: test_imsave
def test_imsave(fmt):
if fmt in ["jpg", "jpeg", "tiff"]:
pytest.importorskip("PIL")
has_alpha = fmt not in ["jpg", "jpeg"]
# 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.
np.random.seed(1)
# The height of 1856 pixels was selected because going through creating an
# actual dpi=100 figure to save the image to a Pillow-provided format would
# cause a rounding error resulting in a final image of shape 1855.
data = np.random.rand(1856, 2)
buff_dpi1 = io.BytesIO()
plt.imsave(buff_dpi1, data, format=fmt, dpi=1)
buff_dpi100 = io.BytesIO()
plt.imsave(buff_dpi100, data, format=fmt, dpi=100)
buff_dpi1.seek(0)
arr_dpi1 = plt.imread(buff_dpi1, format=fmt)
buff_dpi100.seek(0)
arr_dpi100 = plt.imread(buff_dpi100, format=fmt)
assert arr_dpi1.shape == (1856, 2, 3 + has_alpha)
assert arr_dpi100.shape == (1856, 2, 3 + has_alpha)
assert_array_equal(arr_dpi1, arr_dpi100)
示例9: main
def main():
plt.figure(0)
plt.xlim(0,2416)
plt.ylim(1678,0)
im=plt.imread('../final_img.png')
implot=plt.imshow(im)
plt.axis('off')
path_list=open(sys.argv[1],'r').read().splitlines()
i=0
# add '.txt' if needed
for path in path_list:
latlong=[[float(f) for f in line.split(',')[9:11]] for line in open(sys.argv[2]+path).read().splitlines()]
# common plots for all the paths
plt.figure(0)
plot_given_plot(latlong,plt)
# different plots for all the paths
i=i+1
plt.figure(i)
plt.xlim(0,2416)
plt.ylim(1678,0)
im=plt.imread('../final_img.png')
implot=plt.imshow(im)
plt.axis('off')
plot_given_plot(latlong,plt)
plt.savefig(sys.argv[3]+str(i),ext='png',close=False,verbose=True,dpi=350,bbox_inches='tight',pad_inches=0)
plt.figure(0)
plt.savefig(sys.argv[3]+'all',ext='png',close=False,verbose=True,dpi=350,bbox_inches='tight',pad_inches=0)
示例10: main
def main():
f_ultrasounds = [img for img in glob.glob("/home/r/NerveSegmentation/train/*.tif") if 'mask' not in img]
# f_ultrasounds.sort()
f_masks = [fimg_to_fmask(fimg) for fimg in f_ultrasounds]
images_shown = 0
for f_ultrasound, f_mask in zip(f_ultrasounds, f_masks):
img = plt.imread(f_ultrasound)
mask = plt.imread(f_mask)
if mask_not_blank(mask):
# plot_image(grays_to_RGB(img), title=f_ultrasound)
# plot_image(grays_to_RGB(mask), title=f_mask)
f_combined = f_ultrasound + " & " + f_mask
#img = image_with_mask(img, mask)
plot_image(image_with_mask(img, mask), title=f_combined)
plot_image(img, title=f_combined)
print('plotted:', f_combined)
images_shown += 1
if images_shown >= IMAGES_TO_SHOW:
break
df = []
MyImg = np.zeros([len(img), len(img[0])],dtype=np.uint8)
f_ultrasounds = [img for img in glob.glob("/home/r/NerveSegmentation/test/*.tif")]
for f_ultrasound in zip(f_ultrasounds):
img = plt.imread(f_ultrasound)
df.append(img)
示例11: get_image
def get_image(image_name, test=False):
"""
Return the image
params
------
image_name: string, name of the image
returns
-------
image, calc: (ndarray, ndarray)
returns a tuple of images, one being a sculpture, the other a mask
Returns None, None if the mask doesn't exist
"""
try:
image = imread(os.path.join(data_all_path, image_name))[:-1][::-1]
calc = imread(os.path.join(
masks_all_path,
image_name[:-3] + 'png'))
except IOError:
print "IOError %s" % os.path.join(masks_train_path,
image_name[:-3] + 'png')
return None, None
return image, calc
示例12: main
def main():
f_ultrasounds = [img for img in glob.glob("../input/train/*.tif") if 'mask' not in img]
# f_ultrasounds.sort()
f_masks = [fimg_to_fmask(fimg) for fimg in f_ultrasounds]
images_shown = 0
for f_ultrasound, f_mask in zip(f_ultrasounds, f_masks):
img = plt.imread(f_ultrasound)
mask = plt.imread(f_mask)
if mask_not_blank(mask):
# plot_image(grays_to_RGB(img), title=f_ultrasound)
# plot_image(grays_to_RGB(mask), title=f_mask)
f_combined = f_ultrasound + " & " + f_mask
plot_image(image_with_mask(img, mask), title=f_combined)
print('plotted:', f_combined)
images_shown += 1
if images_shown >= IMAGES_TO_SHOW:
break
示例13: convert_single_file_from_ilastik
def convert_single_file_from_ilastik( image_path, segmentation_path, out_path ):
"""Reads a file that was segmented with ilastik and turns it into a
file as seedwater would create it.
Parameters
----------
image_path : string
path to the image file
segmentation_path : string
path to the ilastik segmented image file
out_path : string
where the converted file should be stored
"""
full_image = plt.imread(image_path)
segmented_image = plt.imread(segmentation_path)
seed_image = create_seeds_from_image(segmented_image)
segmentation = create_segmentation_from_seeds( full_image, seed_image )
cv2.imwrite(out_path, segmentation)
示例14: __init__
def __init__(self, photo_string, art_string, content=0.001, style=0.2e6, total_var=0.1e-7):
# load network
self.net = build_model()
# load layers
layers = ['conv4_2', 'conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1']
layers = {k: self.net[k] for k in layers}
self.layers = layers
# load images
im = plt.imread(art_string)
self.art_raw, self.art = prep_image(im)
im = plt.imread(photo_string)
self.photo_raw, self.photo = prep_image(im)
# precompute layer activations for photo and artwork
input_im_theano = T.tensor4()
self._outputs = lasagne.layers.get_output(layers.values(), input_im_theano)
self.photo_features = {k: theano.shared(output.eval({input_im_theano: self.photo}))
for k, output in zip(layers.keys(), self._outputs)}
self.art_features = {k: theano.shared(output.eval({input_im_theano: self.art}))
for k, output in zip(layers.keys(), self._outputs)}
# Get expressions for layer activations for generated image
self.generated_image = theano.shared(floatX(np.random.uniform(-128, 128, (1, 3, IMAGE_W, IMAGE_W))))
gen_features = lasagne.layers.get_output(layers.values(), self.generated_image)
gen_features = {k: v for k, v in zip(layers.keys(), gen_features)}
self.gen_features = gen_features
# set the weights of the regularizers
self._content, self._style, self._total_var = content, style, total_var
示例15: test_load_from_url
def test_load_from_url():
path = Path(__file__).parent / "baseline_images/test_image/imshow.png"
url = ('file:'
+ ('///' if sys.platform == 'win32' else '')
+ path.resolve().as_posix())
plt.imread(url)
plt.imread(urllib.request.urlopen(url))