本文整理汇总了Python中scipy.misc.imread函数的典型用法代码示例。如果您正苦于以下问题:Python imread函数的具体用法?Python imread怎么用?Python imread使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了imread函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: batch_predict
def batch_predict(filenames, net):
"""
Get the features for all images from filenames using a network
Inputs:
filenames: a list of names of image files
Returns:
an array of feature vectors for the list of files given
"""
N, C, H, W = net.blobs[net.inputs[0]].data.shape
F = net.blobs[net.outputs[0]].data.shape[1]
Nf = len(filenames)
Hi, Wi, _ = imread(filenames[0]).shape
allftrs = np.zeros((Nf, F))
for i in range(0, Nf, N):
in_data = np.zeros((N, C, H, W), dtype=np.float32)
batch_range = range(i, min(i+N, Nf))
batch_filenames = [filenames[j] for j in batch_range]
Nb = len(batch_range)
batch_images = np.zeros((Nb, 3, H, W))
for j,fname in enumerate(batch_filenames):
im = imread(fname)
# change grayscale to RGB
if len(im.shape) == 2:
im = np.tile(im[:,:,np.newaxis], (1,1,3))
# lots of steps here to convert a scipy imread image to
# the dimensions and channel ordering that caffe expects
# Briefly, scipy.io.imread returns a HxWxC array in RGB channel order,
# whereas we need a CxHxW array in BGR order and subtract the mean
# RGB -> BGR
# im = im[:,:,(2,1,0)]
# mean subtraction
#im = im - np.array([103.939, 116.779, 123.68])
# resize
im = imresize(im, (H, W))
MEAN_FILE = '/afs/cs.stanford.edu/u/anenberg/scr/CS231N/examples/UCFff/mean.npy'
# get channel in correct dimension
im = np.transpose(im, (2, 0, 1))
im = im - np.load(MEAN_FILE)
batch_images[j,:,:,:] = im
# insert into correct place
in_data[0:len(batch_range), :, :, :] = batch_images
# predict features
ftrs = predict(in_data, net)
for j in range(len(batch_range)):
allftrs[i+j,:] = ftrs[j,:]
print 'Done %d/%d files' % (i+len(batch_range), len(filenames))
return allftrs
示例2: searchPic
def searchPic():
searchTerm = kwords.get()
searchTerm = searchTerm.replace(' ','%20')
url = ('https://ajax.googleapis.com/ajax/services/search/images?v=1.0&q=' +
searchTerm+ '&userip=INSERT-USER-IP')
request = urllib2.Request(url)
response = urllib2.urlopen(request)
# Process the JSON string.
results = simplejson.load(response)
imgURL = results['responseData']['results'][0]['unescapedUrl']
imgName = imgURL.split('/')[-1]
img_temp = urllib.URLopener().retrieve(imgURL, imgName)
img_array = imread(img_temp[0])
url_label.config(text=imgURL)
imgLF.image = imread(imgName, flatten=True)
imgLF.image_clr = imread(imgName)
ax1.imshow(imgLF.image, cmap=plt.cm.gray)
canvas.show()
refresh.config(state=NORMAL, command=refresh_func)
blur.config(state=NORMAL, command=blur_func)
sharpen.config(state=NORMAL, command=sharpen_func)
smooth.config(state=NORMAL, command=smooth_func)
edge.config(state=NORMAL, command=edge_func)
#contrast.config(state=NORMAL, command=contrast_func)
color.config(state=NORMAL, command=color_func)
decolor.config(state=NORMAL, command=decolor_func)
brighten.config(state=NORMAL, command=brighten_func)
darken.config(state=NORMAL, command=darken_func)
示例3: computeDiff
def computeDiff(file1, file2):
# read images as 2D arrays (convert to grayscale for simplicity)
img1 = to_grayscale(imread(file1).astype(float))
img2 = to_grayscale(imread(file2).astype(float))
# compare
n_m, n_0 = compare_images(img1, img2)
return n_m*1.0/img1.size
示例4: getHaar
def getHaar (filepath, row, col, Npos, Nneg):
Nimg = Npos + Nneg
Nfeatures = 295936 #change this number if you need to use more/less features
features = np.zeros((Nfeatures, Nimg))
files = glob.glob(filepath+ "faces/*.jpg")
for i in xrange (Npos):
print "\nComputing Haar Face ",i
imgGray = misc.imread (files[i], flatten=1) #array of floats, gray scale image
if (i < Npos):
# convert to integral image
intImg = np.zeros((row+1,col+1))
intImg [1:row+1,1:col+1] = np.cumsum(cumsum(imgGray,axis=0),axis=1)
# compute features
features [:,i] = computeFeature(intImg,row,col,Nfeatures)
files = glob.glob(filepath+ "background/*.jpg")
for i in xrange (Nneg):
print "\nComputing Haar Background ",i
imgGray = misc.imread (files[i], flatten=1) #array of floats, gray scale image
if (i < Nneg):
# convert to integral image
intImg = np.zeros((row+1,col+1))
intImg [1:row+1,1:col+1] = np.cumsum(cumsum(imgGray,axis=0),axis=1)
# print intImg.shape
# import pdb pdb.set_trace()
# compute features
features[:,i+Npos] = computeFeature(intImg,row,col,Nfeatures)
# print "feat ", features[1000,:]
return features
示例5: copy_incorrect
def copy_incorrect(in_folder, out_folder, incorrect_files="snapshotVGG1-5-test.txt"):
from scipy.misc import imread, imsave, imrotate
print(incorrect_files)
if os.path.exists(incorrect_files):
f = open(incorrect_files, "r")
print("File found")
else:
f = open(os.path.join(in_folder, "stats", incorrect_files), "r")
page = f.read()
sources = page.split('\n')
print(sources)
print(len(sources))
count = 0
for source in sources:
if source.find("jpg") >= 0:
fileinfo = source
if source.find(",") >= 0:
fileinfo = source.split(", ")[0]
rotation = source.split(", ")[1]
image = imread(fileinfo)
image = imrotate(image, int(rotation))
else:
image = imread(fileinfo)
if count == 0:
print(fileinfo)
count += 1
destination = os.path.split(fileinfo.replace(in_folder, out_folder))[0]
if not os.path.exists(destination):
os.makedirs(destination)
filename = os.path.split(fileinfo)[1]
# print(os.path.join(destination, filename))
imsave(os.path.join(destination, filename), image)
print("Moved " + str(count) + " files")
示例6: play_color_likeness
def play_color_likeness(df):
'''
INPUT: (1) Pandas DF
OUTPUT: None
Pull 20 images and show the most similar images
as found by euclidean distance from their color histograms.
'''
some_random_files = [random_file_pull(df, yield_all_info=True).next()
for _ in range(20)]
for img_info_tuple in some_random_files:
source_idx = img_info_tuple[0]
direction = img_info_tuple[1]
filename = img_info_tuple[2]
column_direction = 'nearest_10_neighbors_euclidean_' + direction
nearest_image_idx = df[column_direction][source_idx][0]
nearest_image = (df['base_filename'][nearest_image_idx] +
direction + '.png')
print "original image location is {}, {}".format(
df['lat'][source_idx], df['lng'][source_idx])
print "new image location is {}, {}".format(
df['lat'][nearest_image_idx], df['lng'][nearest_image_idx])
print "the indices in the df are {} and {}".format(
source_idx, nearest_image_idx)
print "\n"
fig = plt.figure(figsize=(16, 8))
# Show search image and most similar image in database #
ax = fig.add_subplot(2, 2, 1)
ax.imshow(imread(filename))
ax2 = fig.add_subplot(2, 2, 2)
ax2.imshow(imread(nearest_image))
ax.set_xticks([])
ax.set_yticks([])
ax2.set_xticks([])
ax2.set_yticks([])
# Plot scatter of nearest 10 and a sampling of all datapoints #
# See plot_nearest_10 for a better visualization #
ax3 = fig.add_subplot(2, 2, 3)
nearest_10 = find_locations_nearest_10(source_idx, direction)
true_loc = df['lat'][source_idx], df['lng'][source_idx]
ax3.scatter(nearest_10[2:, 1], nearest_10[2:, 0])
ax3.scatter(true_loc[1], true_loc[0], color='#33FFFF',
label='true loc', s=30)
ax3.scatter(nearest_10[0][1], nearest_10[0][0],
color='#00FF00', label='best guess', s=30)
ax3.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc=3, ncol=2,
mode="expand", borderaxespad=0.)
ax4 = fig.add_subplot(2, 2, 4)
ax4.scatter(df['lng'][::10], df['lat'][::10])
ax3.set_xlabel("Longitude")
ax4.set_xlabel("Longitude")
ax4.set_ylabel("Latitude")
ax3.set_ylabel("Latitude")
ax3.set_xlim(-109.5, -102.5)
ax4.set_xlim(-109.5, -102.5)
ax4.set_ylim(37, 41)
ax3.set_ylim(37, 41)
plt.show()
示例7: __init__
def __init__(self, folder, im_type='tif'):
"""
Load a previously acquired series of projections for analysis and
reconstruction.
# folder: Path to folder where projections are stored. Reconstructed
slices will also be saved here.
"""
self.folder = os.path.split(os.path.abspath(folder))[0]
self.p0 = 0
self.cor_offset = 0
self.crop = None, None, None, None
self.num_images = None
self.angles = None
files = [f for f in os.listdir(folder) if f[-4:] == '.%s' % im_type]
im_shape = imread(os.path.join(folder, files[0])).shape
self.im_stack = np.zeros(im_shape + (len(files), ))
for idx, fname in enumerate(files):
sys.stdout.write('\rProgress: [{0:20s}] {1:.0f}%'.format('#' *
int(20*(idx + 1) / len(files)),
100*((idx + 1)/len(files))))
sys.stdout.flush()
f = os.path.join(folder, fname)
self.im_stack[:, :, idx] = imread(f)
self.height = self.im_stack.shape[0]
self.width = self.im_stack.shape[1]
示例8: initialize
def initialize(self, filename):
# read filename
with open(filename) as f:
for line in f:
cline = re.split('\s',line)
# tuple (rgb_filename, gt_filename)
self.flist.append((cline[0], cline[1]))
self.N = len(self.flist)
# get sizes
(rgbname, gtname) = self.flist[0]
rgb = misc.imread(rgbname)
if(gtname.endswith('.png')):
gt = misc.imread(gtname)
else:
gt = np.loadtxt(gtname)
(self.H, self.W, self.CH) = rgb.shape
gtshape = gt.shape
self.HL = gtshape[0]
self.WL = gtshape[1]
if(len(gtshape) == 2):
self.CHL = 1
else:
self.CHL = gtshape[2]
# just retrieve the new sizes
if( (self.data_transformer is not None) and self.data_transformer.isResized() ):
(self.H, self.W) = self.data_transformer.getNewDims()
self.HL = self.H
self.WL = self.W
示例9: doMyTest
def doMyTest(net1):
#myImage = '/Users/shkejriwal/Documents/personal/data/myPics/small_no_glasses.jpg'
#myImage = '/Users/shkejriwal/Documents/personal/data/myPics/small.jpg'
#myImage = '/Users/shkejriwal/Documents/personal/data/myPics/small_sk_closeup.jpg'
myImage1 = '/Users/shkejriwal/Documents/personal/data/myPics/small_full_face.jpg'
myImage2 = '/Users/shkejriwal/Documents/personal/data/myPics/small_full_face_no_glass.jpg'
img1 = scipyMisc.imread(myImage1)
#X1 = prepare1DImage(img1)
X1 = prepare2DImage(img1)
sample1 = load(test=True)[0][6:7]
img2 = scipyMisc.imread(myImage2)
#X2 = prepare1DImage(img2)
X2 = prepare2DImage(img2)
y1 = net1.predict(X1)
y2 = net1.predict(X2)
fig = pyplot.figure(figsize=(6, 3))
ax = fig.add_subplot(1, 2, 1, xticks=[], yticks=[])
plot_sample(X1[0], y1[0],ax)
ax = fig.add_subplot(1, 2, 2, xticks=[], yticks=[])
plot_sample(X2[0], y2[0],ax)
pyplot.show()
示例10: image_compare
def image_compare(df, IMAGES_DIR='/home/ryan/asi_images/'):
'''
takes a list of n image ids and returns sum(n..n-1) n comparisons of r2 difference, r2(fft) difference, and average number of thresholded pixels
'''
img_buffer = {}
return_list = []
artdf = df[['_id', 'images']].copy()
artdf.images = artdf.images.apply(getpath)
paths = artdf[['_id','images']].dropna()
paths.index = paths._id
paths = paths.images
if paths.shape[0] < 2:
return DataFrame([])
for id_pair in combinations(paths.index, 2):
if id_pair[0] in img_buffer:
img1 = img_buffer[id_pair[0]]
else:
img_buffer[id_pair[0]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[0]]), (300,300))))
img1 = img_buffer[id_pair[0]]
if id_pair[1] in img_buffer:
img2 = img_buffer[id_pair[1]]
else:
img_buffer[id_pair[1]] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + paths[id_pair[1]]), (300,300))))
img2 = img_buffer[id_pair[1]]
return_list.append(
[id_pair[0], id_pair[1], \
norm(img1 - img2), \
norm(fft2(img1) - fft2(img2)), \
#mean([sum(img1 > threshold_otsu(img1)), sum(img2 > threshold_otsu(img2))])]
#mean([sum(img1 > 0.9), sum(img2 > 0.9)])]
std(img1)+std(img2)/2.]
)
return DataFrame(return_list, columns=['id1','id2','r2diff', 'fftdiff', 'stdavg'])
示例11: getBatch_
def getBatch_(self, indices):
# format NxCHxWxH
batchRGB = np.zeros((len(indices), self.CH, self.W, self.H), dtype='float32')
batchLabel = np.zeros((len(indices), self.W, self.H), dtype='int32')
k = 0
for i in indices:
(rgbname, gtname) = self.flist[i]
# format: HxWxCH
rgb = misc.imread(rgbname)
if(gtname.endswith('.png')):
gt = misc.imread(gtname)
else:
gt = np.loadtxt(gtname)
gt = gt.astype('uint8')
if(self.data_transformer is not None):
rgb = self.data_transformer.transformData(rgb)
gt = self.data_transformer.transformLabel(gt)
#^ data_transformer outputs in format HxWxCH
# convertion from HxWxCH to CHxWxH
batchRGB[k,:,:,:] = rgb.astype(np.float32).transpose((2,1,0))
batchLabel[k,:,:] = gt.astype(np.int32).transpose((1,0))
k += 1
#ipdb.set_trace()
if(self.weights_classes_flag):
return (batchRGB, batchLabel, self.weights_classes)
else:
return (batchRGB, batchLabel)
示例12: repeated_sales
def repeated_sales(df, artistname, artname, r2thresh=7000, fftr2thresh=10000, IMAGES_DIR='/home/ryan/asi_images/'):
"""
Takes a dataframe, artistname and artname and tries to decide, via image matching, if there is a repeat sale. Returns a dict of lot_ids, each entry a list of repeat sales
"""
artdf = df[(df['artistID']==artistname) & (df['artTitle']==artname)]
artdf.images = artdf.images.apply(getpath)
paths = artdf[['_id','images']].dropna()
id_dict = {}
img_buffer = {}
already_ordered = []
for i, path_i in paths.values:
id_dict[i] = []
img_buffer[i] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_i), (300,300))))
for j, path_j in paths[paths._id != i].values:
if j > i and j not in already_ordered:
if j not in img_buffer.keys():
img_buffer[j] = img_as_float(rgb2gray(resize(imread(IMAGES_DIR + path_j), (300,300))))
if norm(img_buffer[i] - img_buffer[j]) < r2thresh and\
norm(fft2(img_buffer[i]) - fft2(img_buffer[j])) < fftr2thresh:
id_dict[i].append(j)
already_ordered.append(j)
for key in id_dict.keys():
if id_dict[key] == []:
id_dict.pop(key)
return id_dict
示例13: test_imsave
def test_imsave(self):
picdir = os.path.join(datapath, "data")
for png in glob.iglob(picdir + "/*.png"):
with suppress_warnings() as sup:
# PIL causes a Py3k ResourceWarning
sup.filter(message="unclosed file")
img = misc.imread(png)
tmpdir = tempfile.mkdtemp()
try:
fn1 = os.path.join(tmpdir, 'test.png')
fn2 = os.path.join(tmpdir, 'testimg')
with suppress_warnings() as sup:
# PIL causes a Py3k ResourceWarning
sup.filter(message="unclosed file")
misc.imsave(fn1, img)
misc.imsave(fn2, img, 'PNG')
with suppress_warnings() as sup:
# PIL causes a Py3k ResourceWarning
sup.filter(message="unclosed file")
data1 = misc.imread(fn1)
data2 = misc.imread(fn2)
assert_allclose(data1, img)
assert_allclose(data2, img)
assert_equal(data1.shape, img.shape)
assert_equal(data2.shape, img.shape)
finally:
shutil.rmtree(tmpdir)
示例14: testsift
def testsift(image1, image2, maxd=1000, distthresh=0.4):
im1 = imread(image1)
print im1[:, :]
im2 = imread(image2)
print im2.shape
kdt = [[], [], []]
d1 = [[], [], []]
d2 = [[], [], []]
C = 3
for channel in range(C):
if C == 1:
_, d1[channel] = sift.descriptors(im1, maxd)
else:
_, d1[channel] = sift.descriptors(im1[:, :, channel], maxd)
print channel, d1[channel].shape
if C == 1:
_, d2[channel] = sift.descriptors(im2, maxd)
else:
_, d2[channel] = sift.descriptors(im2[:, :, channel], maxd)
print channel, d2[channel].shape
kdt[channel] = KDTree(d1[channel])
for desc in d2[channel]:
dist, index = kdt[channel].query(desc)
if distthresh >= dist:
print dist, index
示例15: match
def match(pic1,pic2):
file1 = Image.open(pic1)
file2 = Image.open(pic2)
#img1 = file1.crop((100, 0, 500, 550))
img1 = file1.crop((327, 219, 615, 576))
img1.save("img1.jpg")
# w = file2.size
#h = file2.size
#img2 = file2.crop((100, 0, 500, 550))
img2 = file2.crop((327, 219, 615, 576))
img2.save("img2.jpg")
# read images as 2D arrays (convert to grayscale for simplicity)
img1 = to_grayscale(imread("img1.jpg").astype(float))
img2 = to_grayscale(imread("img2.jpg").astype(float))
#img1 = to_grayscale(img1.astype(float))
#img2 = to_grayscale(img2.astype(float))
# compare
n_m, n_0 = compare_images(img1, img2)
if n_m/img1.size <= 45 and n_0*1.0/img1.size <=45:
return True
else:
return False