本文整理汇总了Python中skimage.util.img_as_float函数的典型用法代码示例。如果您正苦于以下问题:Python img_as_float函数的具体用法?Python img_as_float怎么用?Python img_as_float使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了img_as_float函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: slic_data
def slic_data():
for i in range(uu_num_train+uu_num_test):
print "data %d" %(i+1)
img_name = ''
if i < 10:
img_name = '0' + str(i)
else:
img_name = str(i)
#Read first 70 images as floats
img = img_as_float(io.imread('..\data\\training\image_2\uu_0000' + img_name + '.png'))
img_hsv = color.rgb2hsv(img)
gt_img = img_as_float(io.imread('..\data\\training\gt_image_2\uu_road_0000' + img_name + '.png'))
#Create superpixels for training images
image_segment = slic(img, n_segments = numSegments, sigma = 5)
t, train_indices = np.unique(image_segment, return_index=True)
images_train_indices.append(train_indices)
image = np.reshape(img,(1,(img.shape[0]*img.shape[1]),3))
image_hsv = np.reshape(img_hsv,(1,(img_hsv.shape[0]*img_hsv.shape[1]),3))
#images_train.append([image[0][i] for i in train_indices])
images_train_hsv.append([image_hsv[0][i] for i in train_indices])
#Create gt training image values index at train_indices and converted to 1 or 0
gt_image = np.reshape(gt_img, (1,(gt_img.shape[0]*gt_img.shape[1]),3))
gt_image = [1 if gt_image[0][i][2] > 0 else 0 for i in train_indices]
gt_images_train.append(gt_image)
开发者ID:rudasi,项目名称:road-classification,代码行数:28,代码来源:old_svm_creator.py
示例2: updateParametros
def updateParametros(val):
global p_segmentos, p_sigma, p_compactness, segments, image, cuda_python
if(val == "Python SLIC"):
cuda_python = 0
elif(val == "CUDA gSLICr"):
cuda_python = 1
p_segmentos = int("%d" % (slider_segmentos.val))
p_sigma = slider_sigma.val
p_compactness = slider_compactness.val
image = c_image.copy()
if(cuda_python == 0):
start_time = time.time()
segments = slic(img_as_float(image), n_segments=p_segmentos, sigma=p_sigma, compactness=p_compactness)
print("--- Tempo Python skikit-image SLIC: %s segundos ---" % (time.time() - start_time))
else:
start_time = time.time()
gSLICrInterface.process( p_segmentos)
print("--- Tempo C++/CUDA gSLICr: %s segundos ---" % (time.time() - start_time))
segments = cuda_seg
obj.set_data(mark_boundaries(img_as_float(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)), segments, outline_color=p_outline))
draw()
开发者ID:fernandovieiraf02,项目名称:superpixel,代码行数:26,代码来源:slicParametros.py
示例3: compute_sept_isodata
def compute_sept_isodata(self, mask, thick, septum_base):
"""Method used to create the cell sept_mask using the threshold_isodata
to separate the cytoplasm from the septum"""
cell_mask = mask
if septum_base:
fluor_box = 1 - self.base_box
else:
fluor_box = self.fluor
perim_mask = self.compute_perim_mask(cell_mask, thick)
inner_mask = cell_mask - perim_mask
inner_fluor = (inner_mask > 0) * fluor_box
threshold = threshold_isodata(inner_fluor[inner_fluor > 0])
interest_matrix = inner_mask * (inner_fluor > threshold)
label_matrix = label(interest_matrix, connectivity=2)
interest_label = 0
interest_label_sum = 0
for l in range(np.max(label_matrix)):
if np.sum(img_as_float(label_matrix == l + 1)) > interest_label_sum:
interest_label = l + 1
interest_label_sum = np.sum(img_as_float(label_matrix == l + 1))
return img_as_float(label_matrix == interest_label)
开发者ID:brunomsaraiva,项目名称:eHooke_1.0,代码行数:25,代码来源:cells.py
示例4: createFigure4
def createFigure4(list_file, list_param, corpus_meta, prob_topic_doc, segment_dir, n_topic, output_dir):
for file_item in list_file:
print file_item
for topic in range(n_topic):
print topic
fig = plt.figure()
img = img_as_float(io.imread(img_dir+file_item+'.ppm'))
ax1 = fig.add_subplot(4,4, 1, axisbg='grey')
ax1.set_xticks(()), ax1.set_yticks(())
ax1.imshow(img)
index=2
for param in list_param:
if 'slic' in param:
# print 'test', index
# print corpus_meta[0][1].split('-')[0]
segment_in_file = [item_corpus for item_corpus in corpus_meta if file_item == item_corpus[1].split('-')[0]]
print len(segment_in_file)
segments_res = csv2Array(segment_dir+'/'+file_item+'/'+file_item+'-'+param+'.sup')
img = img_as_float(io.imread(img_dir+file_item+'.ppm'))
output = np.zeros( (len(img), len(img[0])) )
for segment in segment_in_file:
# print prob_topic_doc[int(segment[0])][topic]
output[segments_res == int(segment[2])] = prob_topic_doc[int(segment[0])][topic]
output = mark_boundaries(output, segments_res)
ax1 = fig.add_subplot(4,4, index, axisbg='grey')
# ax1 = fig.add_subplot(5,10, index, axisbg='grey')
ax1.set_xticks(()), ax1.set_yticks(())
ax1.imshow(output)
index += 1
ensure_path(output_dir+'/'+file_item+'/')
plt.savefig(output_dir+'/'+file_item+'/topic-'+str(topic)+'-'+file_item+'.pdf')
plt.clf()
plt.close()
开发者ID:tttor,项目名称:lab1231-sun-prj,代码行数:34,代码来源:make_figure.py
示例5: get
def get(self, uri):
i = imread(uri)
if len(i.shape) == 2:
i = gray2rgb(i)
else:
i = i[:, :, :3]
c = self._image_to_color.get(i)
dbg = self._settings['debug']
if dbg is None:
return c
c, imgs = c
b = splitext(basename(uri))[0]
imsave(join(dbg, b + '-resized.jpg'), imgs['resized'])
imsave(join(dbg, b + '-back.jpg'), img_as_float(imgs['back']))
imsave(join(dbg, b + '-skin.jpg'), img_as_float(imgs['skin']))
imsave(join(dbg, b + '-clusters.jpg'), imgs['clusters'])
return c, {
'resized': join(dbg, b + '-resized.jpg'),
'back': join(dbg, b + '-back.jpg'),
'skin': join(dbg, b + '-skin.jpg'),
'clusters': join(dbg, b + '-clusters.jpg'),
}
开发者ID:algolia,项目名称:color-extractor,代码行数:25,代码来源:from_file.py
示例6: compute_mask
def compute_mask(self, params):
"""Creates the mask for the base image.
Needs the base image, an instance of imageloaderparams
and the clip area, which should be already defined
by the load_base_image method.
Creates the mask by improving the base mask created by the
compute_base_mask method. Applies the mask closing, dilation and
fill holes parameters.
"""
self.compute_base_mask(params)
mask = np.copy(self.base_mask)
closing_matrix = np.ones((params.mask_closing, params.mask_closing))
if params.mask_closing > 0:
# removes small dark spots and then small white spots
mask = img_as_float(morphology.closing(
mask, closing_matrix))
mask = 1 - \
img_as_float(morphology.closing(
1 - mask, closing_matrix))
for f in range(params.mask_dilation):
mask = morphology.erosion(mask, np.ones((3, 3)))
if params.mask_fill_holes:
# mask is inverted
mask = 1 - img_as_float(ndimage.binary_fill_holes(1.0 - mask))
self.mask = mask
self.overlay_mask_base_image()
开发者ID:brunomsaraiva,项目名称:eHooke_1.0,代码行数:32,代码来源:images.py
示例7: svm_predict
def svm_predict(case,svm_classifier):
print "svm predict"
A = []
b = []
if case == 1:
for i in range(uu_num_test):
img_name = i + uu_num_train
if img_name < 10:
img_name = '0' + str(img_name)
else:
img_name = str(img_name)
print "data %d " %(i+uu_num_train)
#Read test images as floats
img = img_as_float(io.imread('..\data\\training\image_2\uu_0000' + img_name + '.png'))
gt_img = img_as_float(io.imread('..\data\\training\gt_image_2\uu_road_0000' + img_name + '.png'))
#Create superpixels for test images
image_segment = slic(img, n_segments = numSegments, sigma = 5)
t, train_indices = np.unique(image_segment, return_index=True)
images_train_indices.append(train_indices)
image = np.reshape(img,(1,(img.shape[0]*img.shape[1]),3))
images_train.append([image[0][i] for i in train_indices])
#Create gt test image values index at train_indices and converted to 1 or 0
gt_image = np.reshape(gt_img, (1,(gt_img.shape[0]*gt_img.shape[1]),3))
gt_image = [1 if gt_image[0][i][2] > 0 else 0 for i in train_indices]
print "len of gt_image: %d with ones: %d" %(len(gt_image),gt_image.count(1))
gt_images_train.append(gt_image)
for i in range(uu_num_test):
for j in range(len(images_train[i])):
A.append(images_train[i][j])
b.append(gt_images_train[i][j])
else:
for i in range(uu_num_train,uu_num_train+uu_num_test):
for j in range(len(images_train_hsv[i])):
#val = np.zeros(6)
#val[0:3] = images_train[i][j]
#val[3:6] = images_train_hsv[i][j]
#A.append(val)
#A.append(images_train[i][j])
A.append(images_train_hsv[i][j])
b.append(gt_images_train[i][j])
A = np.asarray(A)
b = np.asarray(b)
print "A.shape = %s, b.shape = %s" %(A.shape,b.shape)
predicted = svm_classifier.predict(A)
print svm_classifier.score(A,b)
#for i in range(len(gt_images_train)):
# for j in range(len(gt_images_train[i])):
# print "%d, %d" %(gt_images_train[i][j], predicted[j])
print("Classification report for classifier %s:\n%s\n" %(svm_classifier,metrics.classification_report(b,predicted)))
开发者ID:rudasi,项目名称:road-classification,代码行数:59,代码来源:old_svm_creator.py
示例8: run_metrics
def run_metrics(result_dir, metrics_initial_path, noisy_image_dir):
# Add initial metric values
csv_file = open(metrics_initial_path, 'r')
csv_reader = csv.DictReader(csv_file)
metrics_initial = {}
for row in csv_reader:
metrics_initial[row['image']] = {
'q': float(row['q']),
'ocr': float(row['ocr']),
'mse': float(row['mse'])
}
csv_file.close()
results = []
DEFAULT_TEXT = 'Lorem ipsum\ndolor sit amet,\nconsectetur\n\nadipiscing elit.\n\nDonec vel\naliquet velit,\nid congue\nposuere.'
runs = list(xrange(1, 10 + 1, 1))
for run in runs:
# print "--- RUN " + run
run_dir = os.path.join(result_dir, str(run))
for filename in os.listdir(run_dir):
if not filename.endswith('.png'):
continue
image_name = os.path.splitext(filename)[0]
blur, noise, contrast = _parse_image_name(image_name)
image_path = os.path.join(run_dir, filename)
image = util.img_as_float(io.imread(image_path))
ocr = ocr_accuracy(image, DEFAULT_TEXT)
try:
result = next(
r for r in results
if r['image']['name'] == image_name)
except StopIteration:
result = {
'image': {
'name': image_name,
'blur': blur,
'noise': noise,
'contrast': contrast
},
'metrics_initial': metrics_initial[image_name],
'ocr': [],
'q': [],
'mse': [],
}
results.append(result)
result['ocr'].append(ocr)
result['q'].append(q_py(image))
# MSE
ideal_image_name = 'noisy-00-00-' + str(contrast).replace('.', '') + '.png'
ideal_image_path = os.path.join(noisy_image_dir, ideal_image_name)
ideal_image = util.img_as_float(io.imread(ideal_image_path))
mse_val = mse(ideal_image, image)
result['mse'].append(mse_val)
return results
开发者ID:tomasra,项目名称:ga_sandbox,代码行数:55,代码来源:parse.py
示例9: get_images
def get_images(noisy_image_dir, clear_image_dir):
images = []
for noisy_image_file in sorted(os.listdir(noisy_image_dir)):
name, ext = os.path.splitext(noisy_image_file)
contrast = name.split('-')[::-1][0]
clear_image_name = 'clear-00-00-' + contrast + ext
noisy_image_path = os.path.join(noisy_image_dir, noisy_image_file)
clear_image_path = os.path.join(clear_image_dir, clear_image_name)
# Read images
noisy_image = util.img_as_float(io.imread(noisy_image_path))
clear_image = util.img_as_float(io.imread(clear_image_path))
images.append((noisy_image, clear_image, name))
return images
开发者ID:tomasra,项目名称:ga_sandbox,代码行数:13,代码来源:run.py
示例10: create_bin
def create_bin(img, otsu_method=True):
# Binary image created from Threshold, then labelling is done on this image
if otsu_method:
int_img = rescale(img)
t_otsu = threshold_otsu(int_img)
bin_img = (int_img >= t_otsu)
float_img = img_as_float(bin_img)
return float_img
else:
thresh = 400
int_img = rescale(img)
bin_img = (int_img >= thresh)
float_img = img_as_float(bin_img)
return float_img
开发者ID:rtcolling,项目名称:Histology-IHC,代码行数:15,代码来源:ihc_analysis_RC.py
示例11: SegmentationFelz_run_2d
def SegmentationFelz_run_2d(rod):
img = img_as_float(
RodriguesToUnambiguousColor(rod["x"], rod["y"], rod["z"], maxRange=None, centerR=None).astype("uint8")
)
segments_slic = felzenszwalb(img, scale=100, sigma=0.0, min_size=10)
print("Slic number of segments: %d" % len(np.unique(segments_slic)))
return segments_slic
开发者ID:mattbierbaum,项目名称:cuda-plasticity,代码行数:7,代码来源:KMeansPruning.py
示例12: segment
def segment(self):
self.segments = slic(img_as_float(self.img), enforce_connectivity=True)
self.mask = np.zeros(self.img.shape[:2],dtype='int' )
self.mask = self.mask - 1
for (i, segVal) in enumerate(np.unique(self.segments)):
self.mask[segVal == self.segments] = i
self.pixel_list.append(self.Pixel(i))
开发者ID:15cm,项目名称:clothing-classifier,代码行数:7,代码来源:superpixel.py
示例13: build_target
def build_target(args):
target = img_as_float(io.imread(args['target']))
target = color.rgb2gray(target)
ratio = float(target.shape[0]) / float(target.shape[1])
target = transform.resize(target, (sz, int(sz/ratio)))
return target
开发者ID:zverham,项目名称:cs6501_project,代码行数:7,代码来源:rank.py
示例14: superpixels
def superpixels(image):
""" given an input image, create super pixels on it
"""
# we could try to limit the problem of holes in boundary by first over segmenting the image
import matplotlib.pyplot as plt
from skimage.segmentation import felzenszwalb, slic, quickshift
from skimage.segmentation import mark_boundaries
from skimage.util import img_as_float
jac_float = img_as_float(image)
plt.imshow(jac_float)
#segments_fz = felzenszwalb(jac_float, scale=100, sigma=0.5, min_size=50)
segments_slic = slic(jac_float, n_segments=600, compactness=0.01, sigma=0.001
#, multichannel = False
, max_iter=50)
fig, ax = plt.subplots(1, 1, sharex=True, sharey=True, subplot_kw={'adjustable':'box-forced'})
fig.set_size_inches(8, 3, forward=True)
fig.subplots_adjust(0.05, 0.05, 0.95, 0.95, 0.05, 0.05)
#ax[0].imshow(mark_boundaries(jac, segments_fz))
#ax[0].set_title("Felzenszwalbs's method")
ax.imshow(mark_boundaries(jac_float, segments_slic))
ax.set_title("SLIC")
return segments_slic
开发者ID:Remi-C,项目名称:extract_data_from_old_paris_map,代码行数:25,代码来源:jacoubet_watershed.py
示例15: get_saliency_ft
def get_saliency_ft(img_path):
# Saliency map calculation based on:
img = skimage.io.imread(img_path)
img_rgb = img_as_float(img)
img_lab = skimage.color.rgb2lab(img_rgb)
mean_val = np.mean(img_rgb,axis=(0,1))
kernel_h = (1.0/16.0) * np.array([[1,4,6,4,1]])
kernel_w = kernel_h.transpose()
blurred_l = scipy.signal.convolve2d(img_lab[:,:,0],kernel_h,mode='same')
blurred_a = scipy.signal.convolve2d(img_lab[:,:,1],kernel_h,mode='same')
blurred_b = scipy.signal.convolve2d(img_lab[:,:,2],kernel_h,mode='same')
blurred_l = scipy.signal.convolve2d(blurred_l,kernel_w,mode='same')
blurred_a = scipy.signal.convolve2d(blurred_a,kernel_w,mode='same')
blurred_b = scipy.signal.convolve2d(blurred_b,kernel_w,mode='same')
im_blurred = np.dstack([blurred_l,blurred_a,blurred_b])
sal = np.linalg.norm(mean_val - im_blurred,axis = 2)
sal_max = np.max(sal)
sal_min = np.min(sal)
sal = 255 * ((sal - sal_min) / (sal_max - sal_min))
return sal
开发者ID:yhenon,项目名称:pyimgsaliency,代码行数:30,代码来源:saliency.py
示例16: recreate_images
def recreate_images(result_dir, noisy_image_dir):
# Read noisy images first
test_images = {}
for image_name in os.listdir(noisy_image_dir):
if image_name.endswith('.png'):
image_path = os.path.join(noisy_image_dir, image_name)
image = util.img_as_float(io.imread(image_path))
image_name_noext = os.path.splitext(image_name)[0]
test_images[image_name_noext] = image
# Enumerate results - image directories
for image_name in sorted(os.listdir(result_dir)):
image_dir = os.path.join(result_dir, image_name)
if os.path.isdir(image_dir):
print image_name
for result_file in sorted(os.listdir(image_dir)):
if result_file.endswith('.net'):
# Instantiate trained ANN from .net file
net_path = os.path.join(image_dir, result_file)
ann = libfann.neural_net()
ann.create_from_file(net_path)
# Filter the same image which it was trained with
filtered_image = filter_fann(
test_images[image_name], ann)
param_set_name = os.path.splitext(result_file)[0]
io.imsave(
os.path.join(image_dir, param_set_name + '.png'),
filtered_image)
开发者ID:tomasra,项目名称:ga_sandbox,代码行数:27,代码来源:parse.py
示例17: run_ocr
def run_ocr(result_dir, output_file):
DEFAULT_TEXT = 'Lorem ipsum\ndolor sit amet,\nconsectetur\n\nadipiscing elit.\n\nDonec vel\naliquet velit,\nid congue\nposuere.'
csv_file = open(output_file, 'w')
fieldnames = ['image', 'param_set', 'ocr']
writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
writer.writeheader()
# Enumerate images
for image_name in sorted(os.listdir(result_dir)):
image_dir = os.path.join(result_dir, image_name)
if os.path.isdir(image_dir):
print image_name
# Enumerate parameter sets
for result_file in sorted(os.listdir(image_dir)):
if result_file.endswith('.png'):
image_path = os.path.join(image_dir, result_file)
image = util.img_as_float(io.imread(image_path))
ocr = ocr_accuracy(image, DEFAULT_TEXT)
result_ps_name = os.path.splitext(result_file)[0]
# # Write into csv file
result_row = {
'image': image_name,
'param_set': result_ps_name,
'ocr': ocr,
}
writer.writerow(result_row)
csv_file.close()
return None
开发者ID:tomasra,项目名称:ga_sandbox,代码行数:28,代码来源:parse.py
示例18: harris_ones
def harris_ones(img, window_size, k=0.05):
"""Calculate the harris score based on a window function of diagonal ones.
Args:
img The image to use for corner detection.
window_size Size of the window (NxN).
k Weighting parameter during the final scoring (det vs. trace).
Returns:
Corner score image
"""
# Gradients
img = skiutil.img_as_float(img)
imgy, imgx = np.gradient(img)
imgxy = imgx * imgy
imgxx = imgx ** 2
imgyy = imgy ** 2
# window function (matrix of diagonal ones)
window = np.ones((window_size, window_size))
# compute parts of harris matrix
a11 = signal.correlate(imgxx, window, mode="same") / window_size
a12 = signal.correlate(imgxy, window, mode="same") / window_size
a21 = a12
a22 = signal.correlate(imgyy, window, mode="same") / window_size
# compute score per pixel
det_a = a11 * a22 - a12 * a21
trace_a = a11 + a22
return det_a - k * trace_a ** 2
开发者ID:aleju,项目名称:computer-vision-algorithms,代码行数:31,代码来源:harris.py
示例19: harris_gauss
def harris_gauss(img, sigma=1, k=0.05):
"""Calculate the harris score based on a gauss window function.
Args:
img The image to use for corner detection.
sigma The sigma value for the gauss functions.
k Weighting parameter during the final scoring (det vs. trace).
Returns:
Corner score image"""
# Gradients
img = skiutil.img_as_float(img)
imgy, imgx = np.gradient(img)
imgxy = imgx * imgy
imgxx = imgx ** 2
imgyy = imgy ** 2
# compute parts of harris matrix
a11 = ndimage.gaussian_filter(imgxx, sigma=sigma, mode="constant")
a12 = ndimage.gaussian_filter(imgxy, sigma=sigma, mode="constant")
a21 = a12
a22 = ndimage.gaussian_filter(imgyy, sigma=sigma, mode="constant")
# compute score per pixel
det_a = a11 * a22 - a12 * a21
trace_a = a11 + a22
score = det_a - k * trace_a ** 2
return score
开发者ID:aleju,项目名称:computer-vision-algorithms,代码行数:28,代码来源:harris.py
示例20: showPredictionOutput
def showPredictionOutput(self):
image_withText = self.image.copy()
# show the output of the prediction with text
for (i, segVal) in enumerate(np.unique(self.segments)):
CORD = self.centerList[i]
if self.predictionList[i] == "other":
colorFont = (255, 0, 0) # "Blue color for other"
else:
colorFont = (0, 0, 255) # "Red color for ocean"
#textOrg = CORD
#textOrg = tuple(numpy.subtract((10, 10), (4, 4)))
testOrg = (40,40) # need this for the if statment bellow
# for some yet unknown reason CORD does sometime contain somthing like this [[[210 209]] [[205 213]] ...]
# the following if statemnet is to not get a error becouse of this
if len(CORD) == len(testOrg):
#textOrg = tuple(np.subtract(CORD, (12, 0)))
textOrg = CORD
cv2.putText(self.image, self.predictionList[i], textOrg, cv2.FONT_HERSHEY_SIMPLEX, 0.1, colorFont, 3)
markedImage = mark_boundaries(img_as_float(cv2.cvtColor(self.image, cv2.COLOR_BGR2RGB)), self.segments)
else:
pass
cv2.imshow("segmented image", markedImage)
cv2.waitKey(0)
开发者ID:larssbr,项目名称:AURlabCVsimulator,代码行数:28,代码来源:slicSuperpixel_lbp_method.py
注:本文中的skimage.util.img_as_float函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论