本文整理汇总了Python中skimage.io.imshow函数的典型用法代码示例。如果您正苦于以下问题:Python imshow函数的具体用法?Python imshow怎么用?Python imshow使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了imshow函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: align_img
def align_img(image_name, loss_fn=sum_of_squared_diff, max_disp = 15, big=False, name=None, hist_eq = False):
b,g,r = get_bgr(image_name)
if hist_eq == True:
b, g, r = exposure.equalize_hist(b), exposure.equalize_hist(g), exposure.equalize_hist(r)
print("Aligning green and blue: ")
ag = align(g, b, loss_fn=loss_fn, max_disp = max_disp, big=big, name=name)
print("Aligning blue and red: ")
ar = align(r, b, loss_fn=loss_fn, max_disp = max_disp, big=big, name=name)
# create a color image
im_out = np.dstack([ar, ag, b])
plt.show()
# save the image
iname = image_name.split('.')
iname[-1] = 'jpg'
image_name = '.'.join(iname)
fname = 'out_' + image_name
skio.imsave(fname, im_out)
# display the image
skio.imshow(im_out)
plt.show()
skio.show()
开发者ID:girishbalaji,项目名称:girishbalaji.github.io,代码行数:25,代码来源:main.py
示例2: PreprocessImage
def PreprocessImage(path, show_img=False):
# load image
img = io.imread(path)
print("Original Image Shape: ", img.shape)
# we crop image from center
short_egde = min(img.shape[:2])
yy = int((img.shape[0] - short_egde) / 2)
xx = int((img.shape[1] - short_egde) / 2)
crop_img = img[yy : yy + short_egde, xx : xx + short_egde]
# resize to 224, 224
resized_img = transform.resize(crop_img, (224, 224))
if show_img:
io.imshow(resized_img)
# convert to numpy.ndarray
sample = np.asarray(resized_img) * 256
# swap channel from RGB to BGR
sample = sample[:, :, [2,1,0]]
# swap axes to make image from (224, 224, 4) to (3, 224, 224)
sample = np.swapaxes(sample, 0, 2)
sample = np.swapaxes(sample, 1, 2)
# sub mean
normed_img = sample - mean_img
normed_img.resize(1, 3, 224, 224)
return normed_img
开发者ID:hetong007,项目名称:mxnet,代码行数:25,代码来源:mxnet_predict_example.py
示例3: save_segmented_image
def save_segmented_image(self, filepath_image, modality='t1c', show=False):
'''
Creates an image of original brain with segmentation overlay and save it in ./predictions
INPUT (1) str 'filepath_image': filepath to test image for segmentation, including file extension
(2) str 'modality': imaging modality to use as background. defaults to t1c. options: (flair, t1, t1c, t2)
(3) bool 'show': If true, shows output image. defaults to False.
OUTPUT (1) if show is True, shows image of segmentation results
(2) if show is false, returns segmented image.
'''
modes = {'flair': 0, 't1': 1, 't1c': 2, 't2': 3}
segmentation = self.predict_image(filepath_image, show=False)
print 'segmentation = ' + str(segmentation)
img_mask = np.pad(segmentation, (16, 16), mode='edge')
ones = np.argwhere(img_mask == 1)
twos = np.argwhere(img_mask == 2)
threes = np.argwhere(img_mask == 3)
fours = np.argwhere(img_mask == 4)
test_im = io.imread(filepath_image)
test_back = test_im.reshape(5, 216, 160)[modes[modality]]
# overlay = mark_boundaries(test_back, img_mask)
gray_img = img_as_float(test_back)
# adjust gamma of image
image = adjust_gamma(color.gray2rgb(gray_img), 0.65)
sliced_image = image.copy()
red_multiplier = [1, 0.2, 0.2]
yellow_multiplier = [1, 1, 0.25]
green_multiplier = [0.35, 0.75, 0.25]
blue_multiplier = [0, 0.25, 0.9]
print str(len(ones))
print str(len(twos))
print str(len(threes))
print str(len(fours))
# change colors of segmented classes
for i in xrange(len(ones)):
sliced_image[ones[i][0]][ones[i][1]] = red_multiplier
for i in xrange(len(twos)):
sliced_image[twos[i][0]][twos[i][1]] = green_multiplier
for i in xrange(len(threes)):
sliced_image[threes[i][0]][threes[i][1]] = blue_multiplier
for i in xrange(len(fours)):
sliced_image[fours[i][0]][fours[i][1]] = yellow_multiplier
#if show=True show the prediction
if show:
print 'Showing...'
io.imshow(sliced_image)
plt.show()
#save the prediction
print 'Saving...'
try:
mkdir_p('./predictions/')
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
except:
io.imsave('./predictions/' + os.path.basename(filepath_image) + '.png', sliced_image)
print 'prediction saved.'
开发者ID:meghamattikalli,项目名称:nn-segmentation-for-lar,代码行数:60,代码来源:BrainSegDCNN_2.py
示例4: doit
def doit(filename):
dat = io.imread(filename)
dat = rgb2gray(dat)
blobs = blob_dog(dat, max_sigma=12, threshold=.25)
blobs[:, 2] = blobs[:, 2] * (2 ** 0.5)
io.imshow(dat)
for blob in blobs:
y, x, r = blob
c = plt.Circle((x, y), r, color='r', linewidth=2, fill=False)
plt.gca().add_patch(c)
plt.show()
print (blobs[:,2].size)
r = (blobs[:,2])
print (r)
print (area_of_circle(r))
avg_area = np.mean(area_of_circle(r))
print (avg_area)
#Distance from average x
avg_x = np.mean(blobs[:,0])
x = (blobs[:,0])
x_dist = (x-avg_x)
print (x_dist)
#Distance from average y
avg_y = np.mean(blobs[:,1])
y = (blobs[:,1])
y_dist = (y-avg_y)
print (y_dist)
return blobs # for potential further processing
开发者ID:hannahwear,项目名称:Research_Programming_Final_Project_Wearh,代码行数:35,代码来源:final_project_script.py
示例5: transform
def transform(self, func, params, sub_dir=None, img_ind=None):
"""
Takes a function and apply to every img_arr in self.img_arr.
Have to option to transform one as a test case
:param sub_dir: The index for the image
:param img_ind: The index of the category of images
"""
# Apply to one test case
if sub_dir is not None and img_ind is not None:
sub_dir_ind = self.label_map[sub_dir]
img_arr = self.img_lst2[sub_dir_ind][img_ind]
img_arr = func(img_arr, **params).astype(float)
io.imshow(img_arr)
plt.show()
# Apply the function and parameters to all the images
elif isinstance(sub_dir, list):
if len(sub_dir) == 1:
sub_dir_ind = self.label_map[sub_dir[0]]
new_img_lst2 = []
for img_arr in self.img_lst2[sub_dir_ind]:
new_img_lst2.append(func(img_arr, **params).astype(float))
self.img_lst2[sub_dir_ind] = new_img_lst2
else:
for dir in sub_dir:
sub_dir_ind = self.label_map[dir]
new_img_lst2 = []
for img_arr in self.img_lst2[sub_dir_ind]:
new_img_lst2.append(func(img_arr, **params).astype(float))
self.img_lst2[sub_dir_ind] = new_img_lst2
else:
new_img_lst2 = []
for img_lst in self.img_lst2:
new_img_lst2.append([func(img_arr, **params).astype(float) for img_arr in img_lst])
self.img_lst2 = new_img_lst2
开发者ID:oxfordBlueDevil,项目名称:Painting-Classification,代码行数:35,代码来源:pipeline.py
示例6: main
def main():
args = vars(parser.parse_args())
filename = os.path.join(os.getcwd(), args["image"][0])
image = skimage.img_as_uint(color.rgb2gray(io.imread(filename)))
subsample = 1
if (not args["subsample"] == 1):
subsample = args["subsample"][0]
image = transform.downscale_local_mean(image, (subsample, subsample))
image = transform.pyramid_expand(image, subsample, 0, 0)
image = exposure.rescale_intensity(image, out_range=(0,args["depth"][0]))
if (args["visualize"]):
io.imshow(image)
io.show()
source = generate_face(image, subsample, args["depth"][0], FLICKER_SPEED)
if source:
with open(args["output"][0], 'w') as file_:
file_.write(source)
else:
print "Attempted to generate source code, failed."
开发者ID:kctess5,项目名称:sad_robot,代码行数:27,代码来源:main.py
示例7: detectOpticDisc
def detectOpticDisc(image):
kernel = octagon(10, 10)
thresh = threshold_otsu(image[:,:,1])
binary = image > thresh
print binary.dtype
luminance = convertToHLS(image)[:,:,2]
t = threshold_otsu(luminance)
t = erosion(luminance, kernel)
labels = segmentation.slic(image[:,:,1], n_segments = 3)
out = color.label2rgb(labels, image[:,:,1], kind='avg')
skio.imshow(out)
x, y = computeCentroid(t)
print x, y
rows, cols, _ = image.shape
p1 = closing(image[:,:,1],kernel)
p2 = opening(p1, kernel)
p3 = reconstruction(p2, p1, 'dilation')
p3 = p3.astype(np.uint8)
#g = dilation(p3, kernel)-erosion(p3, kernel)
#g = rank.gradient(p3, disk(5))
g = cv2.morphologyEx(p3, cv2.MORPH_GRADIENT, kernel)
#markers = rank.gradient(p3, disk(5)) < 10
markers = drawCircle(rows, cols, x, y, 85)
#markers = ndimage.label(markers)[0]
#skio.imshow(markers)
g = g.astype(np.uint8)
#g = cv2.cvtColor(g, cv2.COLOR_GRAY2RGB)
w = watershed(g, markers)
print np.max(w), np.min(w)
w = w.astype(np.uint8)
#skio.imshow(w)
return w
开发者ID:fvermeij,项目名称:cad-doge,代码行数:35,代码来源:opticDiscVesselDetection.py
示例8: show_user_imgs
def show_user_imgs(imgs):
'''
Display images to new_user and prompt for response (Like / NoLike)
Keep track of preferences in a list.
INPUT: list of pairs, (username, img_id)
OUTPUT: np.array of new_user's preferences (zero or one)
'''
# initialize the list of preferences
likes = []
for img in imgs:
# generate the path to the image
fname = '../imgs/{}'.format(img)
# update status to terminal
print fname
# show image to user
imshow(fname)
plt.show()
# initialize string of preferences
pref = ''
# logical xor in python is != ... i know, right??
while not pref in ['0', '1']:
# survey whether user liked photo
print 'you entered: {}'.format(pref)
pref = raw_input('Did you like that photo? Yes:1, No:0...')
# keep track of the result in list 'likes'
likes.append(int(pref))
# convert list 'likes' to np.array for better handling downstream
likes = np.array(likes).astype('bool')
return likes
开发者ID:theod07,项目名称:recommend-a-graham,代码行数:31,代码来源:new_user.py
示例9: threshold_image
def threshold_image(image, threshold=0):
"""
This function takes out any values in an image's RGB matrix that are
below the threshold value.
Inputs:
- image: a matrix describing an image with only one channel represented.
- threshold: a value, between 0 and 1, for which if an image matrix's
value is below, will be set to 0, and if above, will be
set to 1.
If the threshold is set to 0, then an Otsu thresholding will
be returned.
Outputs:
- thresholded_image: a matrix representation of the thresholded image.
this is essentially a black and white image.
- thresh: the threshold value
To screen: the black-and-white image representation.
-
"""
if threshold == 0:
thresh = threshold_otsu(image)
if threshold != 0:
thresh = threshold
thresholded_image = closing(image > thresh, square(3), out=None)
imshow(thresholded_image)
return thresholded_image, thresh
开发者ID:runstadler-lab,项目名称:Seal-H3N8-Image-Analysis,代码行数:32,代码来源:rgprocessing.py
示例10: predict_image
def predict_image(self, test_img, show=False):
'''
predicts classes of input image
INPUT (1) str 'test_image': filepath to image to predict on
(2) bool 'show': True to show the results of prediction, False to return prediction
OUTPUT (1) if show == False: array of predicted pixel classes for the center 208 x 208 pixels
(2) if show == True: displays segmentation results
'''
imgs = io.imread(test_img).astype('float').reshape(5,240,240)
plist = []
# create patches from an entire slice
for img in imgs[:-1]:
if np.max(img) != 0:
img /= np.max(img)
p = extract_patches_2d(img, (33,33))
plist.append(p)
patches = np.array(zip(np.array(plist[0]), np.array(plist[1]), np.array(plist[2]), np.array(plist[3])))
# predict classes of each pixel based on model
full_pred = self.model_comp.predict_classes(patches)
fp1 = full_pred.reshape(208,208)
if show:
io.imshow(fp1)
plt.show
else:
return fp1
开发者ID:naldeborgh7575,项目名称:brain_segmentation,代码行数:27,代码来源:Segmentation_Models.py
示例11: draw_window
def draw_window(frame):
# setup initial location of window
r,h,c,w = 250,90,400,125 # simply hardcoded the values
track_window = (c,r,w,h)
# set up the ROI for tracking
roi = frame[r:r+h, c:c+w]
hsv_roi = cv2.cvtColor(roi, cv2.COLOR_BGR2HSV)
mask = cv2.inRange(hsv_roi, np.array((0., 60.,32.)), np.array((180.,255.,255.)))
roi_hist = cv2.calcHist([hsv_roi],[0],mask,[180],[0,180])
cv2.normalize(roi_hist,roi_hist,0,255,cv2.NORM_MINMAX)
# Setup the termination criteria, either 10 iteration or move by atleast 1 pt
term_crit = ( cv2.TERM_CRITERIA_EPS | cv2.TERM_CRITERIA_COUNT, 10, 1 )
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
dst = cv2.calcBackProject([hsv],[0],roi_hist,[0,180],1)
# apply meanshift to get the new location
ret, track_window = cv2.CamShift(dst, track_window, term_crit)
# Draw it on image
pts = cv2.boxPoints(ret)
pts = np.int0(pts)
img2 = cv2.polylines(frame,[pts],True, 255,2)
io.imshow(img2)
开发者ID:KentChun33333,项目名称:VistinoEventDes,代码行数:25,代码来源:MP4_Extraction.py
示例12: just_do_it
def just_do_it(limit_cont):
fig = plt.figure(facecolor='black')
plt.gray()
print("Rozpoczynam przetwarzanie obrazow...")
for i in range(20):
img = data.imread(images[i])
gray_img = to_gray(images[i]) # samoloty1.pdf
#gray_img = to_gray2(images[i], 1001, 0.2, 5, 9, 12) # samoloty2.pdf
#gray_img = to_gray2(images[i], 641, 0.2, 5, 20, 5) # samoloty3.pdf
conts = find_contours(gray_img, limit_cont)
centrs = [find_centroid(cont) for cont in conts]
ax = fig.add_subplot(4,5,i)
ax.set_yticks([])
ax.set_xticks([])
io.imshow(img)
print("Przetworzono: " + images[i])
for n, cont in enumerate(conts):
ax.plot(cont[:, 1], cont[:, 0], linewidth=2)
for centr in centrs:
ax.add_artist(plt.Circle(centr, 5, color='white'))
fig.tight_layout()
#plt.show()
plt.savefig('samoloty3.pdf')
开发者ID:likeMyCode,项目名称:HCInteraction,代码行数:29,代码来源:find_planes.py
示例13: test
def test(frame):
hsv = cv2.cvtColor(frame, cv2.COLOR_BGR2HSV)
lower_white = np.array([0,0,200])
upper_white = np.array([300,100,300])
# Threshold the HSV image to get only white colors
mask = cv2.inRange(hsv, lower_white, upper_white)
gray = cv2.cvtColor(mask, cv2.COLOR_BAYER_GB2GRAY)
gradX = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)
# subtract the y-gradient from the x-gradient
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)
# blur and threshold the image
blurred=cv2.blur(gray,(9,9))
blurred = cv2.blur(gradient, (9, 9))
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)
image, contours,hierarchy= cv2.findContours(closed,
cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
img= cv2.drawContours(frame, contours, -1,(0,0,0),3)
io.imshow(img)
开发者ID:KentChun33333,项目名称:VistinoEventDes,代码行数:26,代码来源:MP4_Extraction_v2.py
示例14: background_sub
def background_sub(frame):
'''
out
'''
return gray
io.imshow(img)
开发者ID:KentChun33333,项目名称:VistinoEventDes,代码行数:7,代码来源:MP4_Extraction_v2.py
示例15: main
def main():
imgs = MultiImage(data_dir + '/multipage.tif')
for a, i in zip(range(0, 4), [1, 9, 7, 8]):
fig = plt.figure()
ax = fig.add_axes([-0.1, -0.1, 1.2, 1.2])
# ax.set_axis_off()
im = data.imread('samolot0' + str(i) + '.jpg', as_grey = True)
im = invert(im)
im = process(im)
out = np.ones_like(im)
io.imshow(out)
contours = measure.find_contours(im, 0.9)
for n, contour in enumerate(contours):
plt.plot(contour[:, 1], contour[:, 0], linewidth=2, color = 'white')
plt.savefig(str(a) + '.jpg', bbox_inches = 0, frameon = False)
fig = plt.figure()
grid = AxesGrid(fig, rect = (1, 1, 1), nrows_ncols = (2, 2), axes_pad = 0.1)
for i in range(0, 4):
frame = data.imread(str(i) + '.jpg')
grid[i].imshow(frame)
grid[i].set_xticks([])
grid[i].set_yticks([])
plt.savefig('na3.jpg')
开发者ID:ja999,项目名称:sem5,代码行数:27,代码来源:na3.py
示例16: hsi_equalize_hist
def hsi_equalize_hist():
image=data.astronaut()
h=color.rgb2hsv(image)
h[:,:,2]=exposure.equalize_hist(h[:,:,2])
image_equal=color.hsv2rgb(h)
io.imshow(image_equal)
io.imsave('astronautequal.png',image_equal)
开发者ID:xingnix,项目名称:learning,代码行数:7,代码来源:colorimage.py
示例17: recognize
def recognize(breaker, show, sample, LEVEL, THRESHOLD):
img = io.imread(sample)
if show:
io.imshow(img, 'pil')
res = ''
for cat in breaker.match(img, LEVEL, THRESHOLD):
res += cat.name
print res
开发者ID:WOnder93,项目名称:is-muni-captcha-breaker,代码行数:8,代码来源:captcha_breaker.py
示例18: main
def main():
from skimage import data, io, filters
testfolder='/Users/davidgreenfield/Downloads/pics_boots/'
testimage='B00A0GVP8A.jpg'
image = io.imread(testfolder+testimage,flatten=True) # or any NumPy array!
edges = filters.sobel(image)
io.imshow(edges)
io.show()
开发者ID:dgreenfi,项目名称:ImageRec,代码行数:8,代码来源:image_tests.py
示例19: get_rect
def get_rect(path):
e, img = detect(path)
img = img[40:, :]
imshow(img)
# import Image
# im = Image.fromarray(img)
# im.save("your_file.jpg")
return img
开发者ID:jxieeducation,项目名称:Quick-Hackathon-Side-Project-Experiments-2014,代码行数:8,代码来源:iris.py
示例20: doEigengesichter
def doEigengesichter(self,pos):
dim = int(math.sqrt(self.VT.shape[1]))
mdata = np.zeros((dim,dim))
imageVector = self.VT[pos,:]
for i in range(0,len(imageVector),int(dim)):
row = np.array(imageVector)[i:i+dim]
mdata[int(i/dim),:] = row
io.imshow(mdata)
开发者ID:Twittadrock,项目名称:MachineLearningWS2014,代码行数:8,代码来源:PCAEigengesichter.py
注:本文中的skimage.io.imshow函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论