def test_histogram_of_oriented_gradients(): img = img_as_float(data.astronaut()[:256, :].mean(axis=2)) fd = feature.hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(1, 1)) assert len(fd) == 9 * (256 // 8) * (512 // 8)
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)
def test_rotated_img(): """ The harris filter should yield the same results with an image and it's rotation. """ im = img_as_float(data.astronaut().mean(axis=2)) im_rotated = im.T # Moravec results = peak_local_max(corner_moravec(im), min_distance=10, threshold_rel=0) results_rotated = peak_local_max(corner_moravec(im_rotated), min_distance=10, threshold_rel=0) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() # Harris results = peak_local_max(corner_harris(im), min_distance=10, threshold_rel=0) results_rotated = peak_local_max(corner_harris(im_rotated), min_distance=10, threshold_rel=0) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all() # Shi-Tomasi results = peak_local_max(corner_shi_tomasi(im), min_distance=10, threshold_rel=0) results_rotated = peak_local_max(corner_shi_tomasi(im_rotated), min_distance=10, threshold_rel=0) assert (np.sort(results[:, 0]) == np.sort(results_rotated[:, 1])).all() assert (np.sort(results[:, 1]) == np.sort(results_rotated[:, 0])).all()
def load_batches(): # Here, load 10 batches of size 4 each. # You can also load an infinite amount of batches, if you don't train # in epochs. batch_size = 4 nb_batches = 10 # Here, for simplicity we just always use the same image. astronaut = data.astronaut() astronaut = ia.imresize_single_image(astronaut, (64, 64)) for i in range(nb_batches): # A list containing all images of the batch. batch_images = [] # A list containing IDs per image. This is not necessary for the # background augmentation and here just used to showcase that you # can transfer additional information. batch_data = [] # Add some images to the batch. for b in range(batch_size): batch_images.append(astronaut) batch_data.append((i, b)) # Create the batch object to send to the background processes. batch = ia.Batch( images=np.array(batch_images, dtype=np.uint8), data=batch_data ) yield batch
def test_daisy_normalization(): img = img_as_float(data.astronaut()[:64, :64].mean(axis=2)) descs = daisy(img, normalization='l1') for i in range(descs.shape[0]): for j in range(descs.shape[1]): assert_almost_equal(np.sum(descs[i, j, :]), 1) descs_ = daisy(img) assert_almost_equal(descs, descs_) descs = daisy(img, normalization='l2') for i in range(descs.shape[0]): for j in range(descs.shape[1]): assert_almost_equal(sqrt(np.sum(descs[i, j, :] ** 2)), 1) orientations = 8 descs = daisy(img, orientations=orientations, normalization='daisy') desc_dims = descs.shape[2] for i in range(descs.shape[0]): for j in range(descs.shape[1]): for k in range(0, desc_dims, orientations): assert_almost_equal(sqrt(np.sum( descs[i, j, k:k + orientations] ** 2)), 1) img = np.zeros((50, 50)) descs = daisy(img, normalization='off') for i in range(descs.shape[0]): for j in range(descs.shape[1]): assert_almost_equal(np.sum(descs[i, j, :]), 0) assert_raises(ValueError, daisy, img, normalization='does_not_exist')
def test_binary_descriptors_rotation_crosscheck_true(): """Verify matched keypoints and their corresponding masks results between image and its rotated version with the expected keypoint pairs with cross_check enabled.""" img = data.astronaut() img = rgb2gray(img) tform = tf.SimilarityTransform(scale=1, rotation=0.15, translation=(0, 0)) rotated_img = tf.warp(img, tform, clip=False) extractor = BRIEF(descriptor_size=512) keypoints1 = corner_peaks(corner_harris(img), min_distance=5, threshold_abs=0, threshold_rel=0.1) extractor.extract(img, keypoints1) descriptors1 = extractor.descriptors keypoints2 = corner_peaks(corner_harris(rotated_img), min_distance=5, threshold_abs=0, threshold_rel=0.1) extractor.extract(rotated_img, keypoints2) descriptors2 = extractor.descriptors matches = match_descriptors(descriptors1, descriptors2, cross_check=True) exp_matches1 = np.array([ 0, 2, 3, 4, 5, 6, 9, 11, 12, 13, 14, 17, 18, 19, 21, 22, 23, 26, 27, 28, 29, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46]) exp_matches2 = np.array([ 0, 2, 3, 1, 4, 6, 5, 7, 13, 10, 9, 11, 15, 8, 14, 12, 16, 18, 19, 21, 20, 24, 25, 26, 28, 27, 22, 23, 29, 30, 31, 32, 35, 33, 34, 36]) assert_equal(matches[:, 0], exp_matches1) assert_equal(matches[:, 1], exp_matches2)
def ton_and_color_corrections(): #色调和彩色校正 image=data.astronaut() h1=color.rgb2hsv(image) h2=h1.copy() h1[:,:,1]=h1[:,:,1]*0.5 image1=color.hsv2rgb(h1) h2[:,:,1]=h2[:,:,1]*0.5+0.5 image2=color.hsv2rgb(h2) io.imshow(image) io.imsave('astronaut.png',image) io.imshow(image1) io.imsave('astronautlight.png',image1) io.imshow(image2) io.imsave('astronautdark.png',image2) imagered=image.copy() imagered[:,:,0]=image[:,:,0]*127.0/255+128 io.imsave('astronautred.png',imagered) imageblue=image.copy() imageblue[:,:,2]=image[:,:,2]*127.0/255+128 io.imsave('astronautblue.png',imageblue) imageyellow=image.copy() imageyellow[:,:,0]=image[:,:,0]*127.0/255+128 imageyellow[:,:,1]=image[:,:,1]*127.0/255+128 io.imsave('astronautyellow.png',imageyellow) io.imshow(imageyellow)
def main(): image = data.astronaut() image = ia.imresize_single_image(image, (HEIGHT, WIDTH)) kps = [] for y in range(NB_ROWS): ycoord = BB_Y1 + int(y * (BB_Y2 - BB_Y1) / (NB_COLS - 1)) for x in range(NB_COLS): xcoord = BB_X1 + int(x * (BB_X2 - BB_X1) / (NB_ROWS - 1)) kp = (xcoord, ycoord) kps.append(kp) kps = set(kps) kps = [ia.Keypoint(x=xcoord, y=ycoord) for (xcoord, ycoord) in kps] kps = ia.KeypointsOnImage(kps, shape=image.shape) bb = ia.BoundingBox(x1=BB_X1, x2=BB_X2, y1=BB_Y1, y2=BB_Y2) bbs = ia.BoundingBoxesOnImage([bb], shape=image.shape) seq = iaa.Affine(rotate=45) seq_det = seq.to_deterministic() image_aug = seq_det.augment_image(image) kps_aug = seq_det.augment_keypoints([kps])[0] bbs_aug = seq_det.augment_bounding_boxes([bbs])[0] image_before = np.copy(image) image_before = kps.draw_on_image(image_before) image_before = bbs.draw_on_image(image_before) image_after = np.copy(image_aug) image_after = kps_aug.draw_on_image(image_after) image_after = bbs_aug.draw_on_image(image_after) ia.imshow(np.hstack([image_before, image_after])) imageio.imwrite("bb_aug.jpg", np.hstack([image_before, image_after]))
def test_hog_output_size(): img = img_as_float(data.astronaut()[:256, :].mean(axis=2)) fd = feature.hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(1, 1), block_norm='L1') assert len(fd) == 9 * (256 // 8) * (512 // 8)
def load_images(n_batches=10, sleep=0.0, draw_text=True): batch_size = 4 astronaut = data.astronaut() astronaut = ia.imresize_single_image(astronaut, (64, 64)) kps = ia.KeypointsOnImage([ia.Keypoint(x=15, y=25)], shape=astronaut.shape) counter = 0 for i in range(n_batches): if draw_text: batch_images = [] batch_kps = [] for b in range(batch_size): astronaut_text = ia.draw_text(astronaut, x=0, y=0, text="%d" % (counter,), color=[0, 255, 0], size=16) batch_images.append(astronaut_text) batch_kps.append(kps) counter += 1 batch = ia.Batch( images=np.array(batch_images, dtype=np.uint8), keypoints=batch_kps ) else: if i == 0: batch_images = np.array([np.copy(astronaut) for _ in range(batch_size)], dtype=np.uint8) batch = ia.Batch( images=np.copy(batch_images), keypoints=[kps.deepcopy() for _ in range(batch_size)] ) yield batch if sleep > 0: time.sleep(sleep)
def main(): image = data.astronaut() cv2.namedWindow("aug", cv2.WINDOW_NORMAL) cv2.imshow("aug", image) cv2.waitKey(TIME_PER_STEP) height, width = image.shape[0], image.shape[1] center_x = width // 2 center_y = height // 2 r = int(min(image.shape[0], image.shape[1]) / 3) for deg in cycle(np.arange(0, 360, DEG_PER_STEP)): rad = np.deg2rad(deg-90) point_x = int(center_x + r * np.cos(rad)) point_y = int(center_y + r * np.sin(rad)) direction = deg / 360 aug = iaa.DirectedEdgeDetect(alpha=1.0, direction=direction) img_aug = aug.augment_image(image) img_aug[point_y-POINT_SIZE:point_y+POINT_SIZE+1, point_x-POINT_SIZE:point_x+POINT_SIZE+1, :] =\ np.array([0, 255, 0]) cv2.imshow("aug", img_aug) cv2.waitKey(TIME_PER_STEP)
def test_li_astro_image(): image = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_li(image) ce_actual = _cross_entropy(image, threshold) assert 64 < threshold < 65 assert ce_actual < _cross_entropy(image, threshold + 1) assert ce_actual < _cross_entropy(image, threshold - 1)
def get_HOG_features(data_path, pickle_name): size = len(data_path) rowPatchCnt = 4 colPatchCnt = 4 var_features = np.zeros((size, colPatchCnt*rowPatchCnt*3)) print var_features.shape image = color.rgb2gray(data.astronaut()) #print image fd, hog_image = hog(image, orientation = 8, pixels_per_cell=(16, 16), cells_per_block = (1,1), visualise=True) print fd im = util.load_image(data_path[0]) #print im #for i in range(size): #if i % 500 == 0: print "{}/{}".format(i, size) #im = util.load_image(data_path[i]) #patchH = im.shape[0] / rowPatchCnt #patchW = im.shape[1] / colPatchCnt #pass #im = np.array(im) pass
def test_astronaut(): from skimage import data from skimage import color from skimage.transform import resize in_shape = (200, 200) n_imgs = 1 astronaut = resize(color.rgb2gray(data.astronaut()), in_shape).astype( np.float32) astronaut -= astronaut.min() astronaut /= astronaut.max() imgs = astronaut.reshape((n_imgs,)+in_shape) model = cnnr.models.fg11_ht_l3_1_description extractor = cnnr.BatchExtractor(in_shape, model) feat_set = extractor.extract(imgs) assert feat_set.shape == (n_imgs, 10, 10, 256) feat_set.shape = n_imgs, -1 test_chunk_computed = feat_set[0, 12798:12802] test_chunk_expected = np.array( [0.028979, 0.03315, 0.024466, 0.009412], dtype=np.float32) assert_allclose(test_chunk_computed, test_chunk_expected, rtol=RTOL, atol=ATOL)
def main(): image = data.astronaut() image = ia.imresize_single_image(image, (64, 64)) print("image shape:", image.shape) print("Press any key or wait %d ms to proceed to the next image." % (TIME_PER_STEP,)) k = [ 1, 3, 5, 7, (3, 3), (1, 11) ] cv2.namedWindow("aug", cv2.WINDOW_NORMAL) cv2.resizeWindow("aug", 64*NB_AUGS_PER_IMAGE, 64) for ki in k: aug = iaa.MedianBlur(k=ki) img_aug = [aug.augment_image(image) for _ in range(NB_AUGS_PER_IMAGE)] img_aug = np.hstack(img_aug) print("dtype", img_aug.dtype, "averages", np.average(img_aug, axis=tuple(range(0, img_aug.ndim-1)))) title = "k=%s" % (str(ki),) img_aug = ia.draw_text(img_aug, x=5, y=5, text=title) cv2.imshow("aug", img_aug[..., ::-1]) # here with rgb2bgr cv2.waitKey(TIME_PER_STEP)
def color_segment(): image=data.astronaut() r=np.uint8((image[:,:,0]>100 ) & (image[:,:,1]<100) & (image[:,:,2]<100)) io.imsave('astronautsegr.png',r*255) g=np.uint8((image[:,:,0]<100 ) & (image[:,:,1]>100) & (image[:,:,2]<100)) io.imsave('astronautsegg.png',g*255) b=np.uint8((image[:,:,0]<100 ) & (image[:,:,1]<100) & (image[:,:,2]>100)) io.imsave('astronautsegb.png',b*255)
def test_threshold_minimum(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_minimum(camera) assert_equal(threshold, 76) astronaut = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_minimum(astronaut) assert_equal(threshold, 114)
def main(): im = astronaut() patches = extract_patches_2d(im, (96, 96), 10, random_state=0) # save these files on disk file_names = ['sample_{}.png'.format(x) for x in range(10)] for idx, filename in enumerate(file_names): patch_this = patches[idx] if not exists(filename): imsave(filename, patch_this)
def test_hog_output_equivariance_multichannel(): img = data.astronaut() img[:, :, (1, 2)] = 0 hog_ref = feature.hog(img, multichannel=True, block_norm='L1') for n in (1, 2): hog_fact = feature.hog(np.roll(img, n, axis=2), multichannel=True, block_norm='L1') assert_almost_equal(hog_ref, hog_fact)
def test_histogram_of_oriented_gradients_output_correctness(): img = color.rgb2gray(data.astronaut()) correct_output = np.load(os.path.join(si.data_dir, 'astronaut_GRAY_hog.npy')) output = feature.hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(3, 3), feature_vector=True, normalise=False, visualise=False) assert_almost_equal(output, correct_output)
def test_hog_output_correctness_l2hys_norm(): img = color.rgb2gray(data.astronaut()) correct_output = np.load( os.path.join(data_dir, 'astronaut_GRAY_hog_L2-Hys.npy')) output = feature.hog(img, orientations=9, pixels_per_cell=(8, 8), cells_per_block=(3, 3), block_norm='L2-Hys', feature_vector=True, transform_sqrt=False, visualize=False) assert_almost_equal(output, correct_output)
def color_edge(): image=data.astronaut() r=np.abs(filters.sobel(image[:,:,0])) r=np.uint8(r/r.max()*255) io.imsave('astronautedger.png',r) g=np.abs(filters.sobel(image[:,:,1])) g=np.uint8(g/g.max()*255) io.imsave('astronautedgeg.png',g) b=np.abs(filters.sobel(image[:,:,2])) b=np.uint8(b/b.max()*255) io.imsave('astronautedgeb.png',b)
def setUp(self): self.data = rgb2gray(astronaut()) # parameters for test self.pad_size = 32 self.tile_size = 64 # split the data and discard extra dimension, not needed here. self.split_data = su.split_img_with_padding( self.data.reshape((1, 512, 512)), self.tile_size, self.pad_size)[:, 0]
def test_num_peaks(): """For a bunch of different values of num_peaks, check that peak_local_max returns exactly the right amount of peaks. Test is run on the astronaut image in order to produce a sufficient number of corners""" img_corners = corner_harris(rgb2gray(data.astronaut())) for i in range(20): n = np.random.random_integers(20) results = peak_local_max(img_corners, num_peaks=n) assert (results.shape[0] == n)
def test_instanciate_segmentation_algorithm(self): img = img_as_float(astronaut()[::2, ::2]) # wrapped functions provide the same result fn = SegmentationAlgorithm('quickshift', kernel_size=3, max_dist=6, ratio=0.5, random_seed=133) fn_result = fn(img) original_result = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5, random_seed=133) # same segments self.assertTrue(np.array_equal(fn_result, original_result))
def test_adapthist_grayscale(): """Test a grayscale float image """ img = skimage.img_as_float(data.astronaut()) img = rgb2gray(img) img = np.dstack((img, img, img)) with expected_warnings(['precision loss|non-contiguous input']): adapted = exposure.equalize_adapthist(img, kernel_size=(57, 51), clip_limit=0.01, nbins=128) assert img.shape == adapted.shape assert_almost_equal(peak_snr(img, adapted), 102.078, 3) assert_almost_equal(norm_brightness_err(img, adapted), 0.0529, 3)
def test_threshold_minimum(): camera = skimage.img_as_ubyte(data.camera()) threshold = threshold_minimum(camera) assert threshold == 76 threshold = threshold_minimum(camera, bias='max') assert threshold == 77 astronaut = skimage.img_as_ubyte(data.astronaut()) threshold = threshold_minimum(astronaut) assert threshold == 117
def periodic_reference_test(): img = data.astronaut() img = rgb2gray(img) s = np.linspace(0, 2 * np.pi, 400) x = 220 + 100 * np.cos(s) y = 100 + 100 * np.sin(s) init = np.array([x, y]).T snake = active_contour_model(gaussian_filter(img, 3), init, alpha=0.015, beta=10, w_line=0, w_edge=1, gamma=0.001) refx = [299, 298, 298, 298, 298, 297, 297, 296, 296, 295] refy = [98, 99, 100, 101, 102, 103, 104, 105, 106, 108] assert_equal(np.array(snake[:10, 0], dtype=np.int32), refx) assert_equal(np.array(snake[:10, 1], dtype=np.int32), refy)
def test_warp_identity(): img = img_as_float(rgb2gray(data.astronaut())) assert len(img.shape) == 2 assert np.allclose(img, warp(img, AffineTransform(rotation=0))) assert not np.allclose(img, warp(img, AffineTransform(rotation=0.1))) rgb_img = np.transpose(np.asarray([img, np.zeros_like(img), img]), (1, 2, 0)) warped_rgb_img = warp(rgb_img, AffineTransform(rotation=0.1)) assert np.allclose(rgb_img, warp(rgb_img, AffineTransform(rotation=0))) assert not np.allclose(rgb_img, warped_rgb_img) # assert no cross-talk between bands assert np.all(0 == warped_rgb_img[:, :, 1])
def test_collection_viewer(): img = data.astronaut() img_collection = tuple(pyramid_gaussian(img)) view = CollectionViewer(img_collection) make_key_event(48) view.update_index('', 2), assert_equal(view.image, img_collection[2]) view.keyPressEvent(make_key_event(53)) assert_equal(view.image, img_collection[5]) view._format_coord(10, 10)
import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage.color import rgb2gray original = data.astronaut() print(original.shape) grayscale = rgb2gray(original) print((grayscale[0])) fig, axes = plt.subplots(1, 2, figsize=(8, 4)) ax = axes.ravel() ax[0].imshow(original) ax[0].set_title("Original") ax[1].imshow(grayscale, cmap=plt.cm.gray) ax[1].set_title("Grayscale") fig.tight_layout() plt.show()
""" Display a labels layer above of an image layer using the add_labels and add_image APIs """ from skimage import data from skimage.color import rgb2gray from skimage.segmentation import slic import napari with napari.gui_qt(): astro = data.astronaut() # initialise viewer with astro image viewer = napari.view(astronaut=rgb2gray(astro), multichannel=False) viewer.layers[0].colormap = 'gray' # add the labels # we add 1 because SLIC returns labels from 0, which we consider background labels = slic(astro, multichannel=True, compactness=20) + 1 label_layer = viewer.add_labels(labels, name='segmentation') # Set the labels layer mode to picker with a string label_layer.mode = 'picker' print(f'The color of label 5 is {label_layer.get_color(5)}')
def main(): parser = argparse.ArgumentParser(description="Check augmenters visually.") parser.add_argument( '--only', default=None, help= "If this is set, then only the results of an augmenter with this name will be shown.", required=False) args = parser.parse_args() images = [ ia.quokka_square(size=(128, 128)), misc.imresize(data.astronaut(), (128, 128)) ] augmenters = [ iaa.Noop(name="Noop"), iaa.OneOf(children=[ iaa.CoarseDropout(p=0.5, size_percent=0.05), iaa.AdditiveGaussianNoise(scale=0.1 * 255), iaa.Crop(percent=0.1) ], name="OneOf"), iaa.AddToHueAndSaturation((-20, 20), per_channel=True, name="AddToHueAndSaturation"), iaa.Crop(px=(0, 8), name="Crop-px"), iaa.Crop(percent=(0, 0.1), name="Crop-percent"), iaa.Fliplr(0.5, name="Fliplr"), iaa.Flipud(0.5, name="Flipud"), iaa.Superpixels(p_replace=0.75, n_segments=50, name="Superpixels"), iaa.Grayscale(0.5, name="Grayscale0.5"), iaa.Grayscale(1.0, name="Grayscale1.0"), iaa.AverageBlur(k=(3, 11), name="AverageBlur"), iaa.GaussianBlur((0, 3.0), name="GaussianBlur"), iaa.MedianBlur(k=(3, 11), name="MedianBlur"), iaa.Sharpen(alpha=(0.1, 1.0), lightness=(0, 2.0), name="Sharpen"), iaa.Emboss(alpha=(0.1, 1.0), strength=(0, 2.0), name="Emboss"), iaa.EdgeDetect(alpha=(0.1, 1.0), name="EdgeDetect"), iaa.DirectedEdgeDetect(alpha=(0.1, 1.0), direction=(0, 1.0), name="DirectedEdgeDetect"), iaa.AdditiveGaussianNoise(loc=0, scale=(0.0, 0.1 * 255), name="AdditiveGaussianNoise"), iaa.Dropout((0.0, 0.1), name="Dropout"), iaa.CoarseDropout(p=0.05, size_percent=(0.05, 0.5), name="CoarseDropout"), iaa.Invert(p=0.5, name="Invert"), iaa.Invert(p=0.5, per_channel=True, name="InvertPerChannel"), iaa.Add((-50, 50), name="Add"), iaa.Add((-50, 50), per_channel=True, name="AddPerChannel"), iaa.AddElementwise((-50, 50), name="AddElementwise"), iaa.Multiply((0.5, 1.5), name="Multiply"), iaa.Multiply((0.5, 1.5), per_channel=True, name="MultiplyPerChannel"), iaa.MultiplyElementwise((0.5, 1.5), name="MultiplyElementwise"), iaa.ContrastNormalization(alpha=(0.5, 2.0), name="ContrastNormalization"), iaa.Affine(scale={ "x": (0.8, 1.2), "y": (0.8, 1.2) }, translate_px={ "x": (-16, 16), "y": (-16, 16) }, rotate=(-45, 45), shear=(-16, 16), order=ia.ALL, cval=(0, 255), mode=ia.ALL, name="Affine"), iaa.PiecewiseAffine(scale=0.03, nb_rows=(2, 6), nb_cols=(2, 6), name="PiecewiseAffine"), iaa.ElasticTransformation(alpha=(0.5, 8.0), sigma=1.0, name="ElasticTransformation"), iaa.PerspectiveTransform(scale=0.1, name="PerspectiveTransform"), ] augmenters.append( iaa.Sequential([iaa.Sometimes(0.2, aug.copy()) for aug in augmenters], name="Sequential")) augmenters.append( iaa.Sometimes(0.5, [aug.copy() for aug in augmenters], name="Sometimes")) for augmenter in augmenters: if args.only is None or augmenter.name == args.only: print("Augmenter: %s" % (augmenter.name, )) grid = augmenter.draw_grid(images, rows=1, cols=16) misc.imshow(grid)
def write_reference_image(): path = '../data/reference_image.png' im = astronaut() imsave(path, im)
""" Add grayscale image =================== Display one grayscale image using the add_image API. """ from skimage import data import napari import numpy as np # simulating a grayscale image here for testing contrast limits adjustments image = data.astronaut().mean(-1) * 100 + 100 image += np.random.rand(*image.shape) * 3000 viewer = napari.view_image(image.astype(np.uint16)) if __name__ == '__main__': napari.run()
from skimage import data import numpy as np import skimage.data as data import skimage.segmentation as seg import skimage.filters as filters import skimage.draw as draw import skimage.color as color import matplotlib.pyplot as plt image = data.astronaut() plt.imshow(image) plt.show() def image_show(image, nrows=1, ncols=1, cmap='gray'): fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=(14, 14)) ax.imshow(image, cmap='gray') ax.axis('off') return fig, ax image_gray = color.rgb2gray(image) image_show(image) def circle_points(resolution, center, radius): radians = np.linspace(0, 2 * np.pi, resolution) c = center[1] + radius * np.cos(radians) r = center[0] + radius * np.sin(radians) return np.array([c, r]).T
def main(): img = imresize(astronaut(), (64, 64)) plt.imshow(img)
def test_warp_coords_example(): image = data.astronaut().astype(np.float32) assert 3 == image.shape[2] tform = SimilarityTransform(translation=(0, -10)) coords = warp_coords(tform, (30, 30, 3)) map_coordinates(image[:, :, 0], coords[:2])
import numpy as np from scipy import ndimage as ndi from matplotlib import pyplot as plt import matplotlib.cm as cm from skimage import data from skimage import color from skimage.util.shape import view_as_blocks # -- get `astronaut` from skimage.data in grayscale l = color.rgb2gray(data.astronaut()) print(l.shape) # -- size of blocks block_shape = (32, 32) # -- see `astronaut` as a matrix of blocks (of shape # `block_shape`) view = view_as_blocks(l, block_shape) # -- collapse the last two dimensions in one flatten_view = view.reshape(view.shape[0], view.shape[1], -1) # -- resampling `astronaut` by taking either the `mean`, # the `max` or the `median` value of each blocks. mean_view = np.mean(flatten_view, axis=2) max_view = np.max(flatten_view, axis=2) median_view = np.median(flatten_view, axis=2)
@adapt_rgb(hsv_value) def sobel_hsv(image): return filters.sobel(image) ###################################################################### # We can use these functions as we would normally use them, but now they work # with both gray-scale and color images. Let's plot the results with a color # image: from skimage import data from skimage.exposure import rescale_intensity import matplotlib.pyplot as plt image = data.astronaut() # 导入宇航员数据 fig, (ax_each, ax_hsv) = plt.subplots(ncols=2, figsize=(14, 7)) # 申明PLOT # We use 1 - sobel_each(image) but this won't work if image is not normalized ax_each.imshow(rescale_intensity( 1 - sobel_each(image))) # sobel运算,并把结果归一化后分布到0-255 SOBEL计算3次 ax_each.set_xticks([]), ax_each.set_yticks([]) ax_each.set_title("Sobel filter computed\n on individual RGB channels") # We use 1 - sobel_hsv(image) but this won't work if image is not normalized ax_hsv.imshow(rescale_intensity(1 - sobel_hsv(image))) # 只计算V ax_hsv.set_xticks([]), ax_hsv.set_yticks([]) ax_hsv.set_title("Sobel filter computed\n on (V)alue converted image (HSV)") ######################################################################
self.SetMenuBar(menubar) return menubar def on_close(self, event): while self.notebook.GetPageCount() > 0: self.notebook.DeletePage(0) event.Skip() if __name__ == '__main__': from skimage.data import camera, astronaut from skimage.io import imread app = wx.App() cf = CanvasFrame(None, autofit=False) cf.set_imgs([astronaut(), 255 - astronaut()]) cf.set_cn(0) cf.Show() app.MainLoop() ''' app = wx.App() cnf = CanvasNoteFrame(None) canvas = cnf.add_img() canvas.set_img(camera()) canvas = cnf.add_img() canvas.set_img(camera()) canvas.set_cn(0) cnf.Show() app.MainLoop()
plt.style.use('ggplot') # ==== DESCRIPTION OF THE NETWORK ==== """ This neural network implements a fun application : painting and image. The input to the network is a position on the image, X = (row, col). The output is the color to paint, Y = (R, G, B). The network is of type fully connected and is composed of 6 hidden layers each containing 64 neurons. The network relies on a supervised type of learning, given that each input position (x, y) is accompanied by its corresponding (r, g, b) label in the picture. """ # ==== CREATION OF THE DATA ==== img = imresize(astronaut(), (64, 64)) plt.imshow(img) # We'll first collect all the positions in the image in our list, xs xs = [] # And the corresponding colors for each of these positions ys = [] # Now loop over the image for row_i in range(img.shape[0]): for col_i in range(img.shape[1]): # And store the inputs xs.append([row_i, col_i]) # And outputs that the network needs to learn to predict ys.append(img[row_i, col_i])
""" Displays an image and sets the theme to new custom theme. """ from skimage import data import napari from napari.utils.theme import available_themes, get_theme, register_theme # create the viewer with an image viewer = napari.view_image(data.astronaut(), rgb=True, name='astronaut') # List themes print('Originally themes', available_themes()) blue_theme = get_theme('dark', False) blue_theme.name = "blue" blue_theme.icon = ( 'rgb(0, 255, 255)' # you can provide colors as rgb(XXX, YYY, ZZZ) ) blue_theme.background = 28, 31, 48 # or as tuples blue_theme.foreground = [45, 52, 71] # or as list blue_theme.primary = '#50586c' # or as hexes blue_theme.current = 'orange' # or as color name register_theme('blue', blue_theme) # List themes print('New themes', available_themes()) # Set theme viewer.theme = 'blue'
# https://www.datacamp.com/community/tutorials/matplotlib-3d-volumetric-data import matplotlib.pyplot as plt from skimage import data astronaut = data.astronaut() ihc = data.immunohistochemistry() hubble = data.hubble_deep_field() # Initialize the subplot panels side by side fig, ax = plt.subplots(nrows=1, ncols=3) # Show an image in each subplot ax[0].imshow(astronaut) ax[0].set_title('Natural image') ax[1].imshow(ihc) ax[1].set_title('Microscopy image') ax[2].imshow(hubble) ax[2].set_title('Telescope image') plt.show()
# noinspection PyPackageRequirements from skimage.data import astronaut # noinspection PyPackageRequirements from PIL import Image # noinspection PyPackageRequirements import numpy as np import pygraphseg ast = astronaut().copy() # noinspection PyUnresolvedReferences seg = pygraphseg.Segment(0.8) image = seg.do(ast, mix_color=True) image = np.asarray(image, dtype=np.uint8) image = Image.fromarray(image) image.show()
def main(_): from skimage import data, transform, img_as_float import matplotlib.pyplot as plt color = False if color: image = data.astronaut() else: # [h,w] -> [h,w,1] image = data.camera() image = np.expand_dims(image, axis=-1) img = img_as_float(image) rows, cols, channels = img.shape noise = np.ones_like(img) * 0.2 * (img.max() - img.min()) noise[np.random.random(size=noise.shape) > 0.5] *= -1 img_noise = img + noise img_noise = np.clip(img_noise, a_min=0, a_max=1) plt.figure() plt.subplot(121) if color: plt.imshow(img) plt.subplot(122) plt.imshow(img_noise) else: plt.imshow(img[:,:,0], cmap='gray') plt.subplot(122) plt.imshow(img_noise[:,:,0], cmap='gray') plt.show() ## TF CALC START image1 = tf.placeholder(tf.float32, shape=[rows, cols, channels]) image2 = tf.placeholder(tf.float32, shape=[rows, cols, channels]) def image_to_4d(image): image = tf.expand_dims(image, 0) return image image4d_1 = image_to_4d(image1) image4d_2 = image_to_4d(image2) print(img.min(), img.max(), img_noise.min(), img_noise.max()) ssim_index = ssim(image4d_1, image4d_2) #, min_val=0.0, max_val=1.0) msssim_index = ms_ssim(image4d_1, image4d_2) #, min_val=0.0, max_val=1.0) with tf.Session() as sess: sess.run(tf.global_variables_initializer()) tf_ssim_none = sess.run(ssim_index, feed_dict={image1: img, image2: img}) tf_ssim_noise = sess.run(ssim_index, feed_dict={image1: img, image2: img_noise}) tf_msssim_none = sess.run(msssim_index, feed_dict={image1: img, image2: img}) tf_msssim_noise = sess.run(msssim_index, feed_dict={image1: img, image2: img_noise}) ###TF CALC END print('tf_ssim_none', tf_ssim_none) print('tf_ssim_noise', tf_ssim_noise) print('tf_msssim_none', tf_msssim_none) print('tf_msssim_noise', tf_msssim_noise)
value = ColorManager.get_front() drawline(ips.img, self.oldp, (y, x), w, value) self.oldp = (y, x) ips.update() def mouse_wheel(self, ips, x, y, d, **key): pass class TestFrame(CanvasFrame, App): def __init__(self, parent): CanvasFrame.__init__(self, parent) App.__init__(self) self.Bind(wx.EVT_ACTIVATE, self.init_image) def init_image(self, event): self.add_img(self.canvas.image) if __name__ == '__main__': app = wx.App() cf = TestFrame(None) cf.set_img(astronaut()) cf.set_cn((0, 1, 2)) bar = cf.add_toolbar() bar.add_tool('C', ColorPicker) bar.add_tool('P', Pencil) bar.add_tool('U', Undo) cf.Show() app.MainLoop()
<https://docs.opencv.org/2.4/doc/user_guide/ug_traincascade.html>`_. """ from skimage import data from skimage.feature import Cascade import matplotlib.pyplot as plt from matplotlib import patches # Load the trained file from the module root. trained_file = data.lbp_frontal_face_cascade_filename() # Initialize the detector cascade. detector = Cascade(trained_file) img = data.astronaut() detected = detector.detect_multi_scale(img=img, scale_factor=1.2, step_ratio=1, min_size=(60, 60), max_size=(123, 123)) plt.imshow(img) img_desc = plt.gca() plt.set_cmap('gray') for patch in detected: img_desc.add_patch( patches.Rectangle((patch['c'], patch['r']),
from scipy.ndimage import zoom from skimage.color import rgb2gray from skimage.filters import gaussian A = SMatrixSubpix.apply smooth_amplitude_loss = SparseSmoothTruncatedAmplitudeLoss.apply from smatrix.util import * from scipy.ndimage.interpolation import rotate # %% M1 = 60 M = np.array([M1, M1]) s = 256 zoomf = 0.35 amp_range = 0.1 amp_min = 0.9 margins = 0 oa = rgb2gray(data.astronaut())[0:0 + s, 150:150 + s] oa1 = oa / oa.max() oa1 = gaussian(oa1, 1 * 1 / zoomf) oa2 = oa1 * amp_range oa2 += amp_min oph = rotate(oa1, 0) ob = zoom(oa2, zoomf) * np.eth(1j * 0.2 * np.pi * zoom(oph, zoomf)) obr = np.zeros((int(ob.shape[0] + 2 * margins), int(ob.shape[1] + 2 * margins))).astype(np.complex64) obr[margins:margins + ob.shape[0], margins:margins + ob.shape[1]] = ob obr1 = np.ones((obr.shape[0], obr.shape[1], 2)).astype(np.float32)
from skimage import data import napari with napari.gui_qt(): viewer = napari.Viewer() # each image is stacked on a layer list (it should be a layer stack =D) # we assign a label to each layer so that we can recover it easily later viewer.add_image(data.astronaut(), name='astronaut') viewer.add_image(data.moon(), name='moon') viewer.add_image(data.camera(), name='camera') # we can access the layers # # viewer.layers[key] # # key can be the key/label assigned to the layer or # an index (integer value) # # `viewer.layers` has type LayerList, which is a list-like layer collection # with built-in reordering and callback hooks. # A layer with an image has the type: napari.layers.image.image.Image # or 'Image layer' # To remove a layer, just use: # viewer.layers.pop(i) # All these codes can be used in the built-in interactive terminal # of Napari, which already has all loaded data on memory
from skimage._shared import testing from skimage._shared.testing import (assert_equal, assert_almost_equal, assert_warns, assert_) from skimage._shared._warnings import expected_warnings from distutils.version import LooseVersion as Version try: import dask except ImportError: DASK_NOT_INSTALLED_WARNING = 'The optional dask dependency is not installed' else: DASK_NOT_INSTALLED_WARNING = None np.random.seed(1234) astro = img_as_float(data.astronaut()[:128, :128]) astro_gray = color.rgb2gray(astro) checkerboard_gray = img_as_float(data.checkerboard()) checkerboard = color.gray2rgb(checkerboard_gray) # versions with one odd-sized dimension astro_gray_odd = astro_gray[:, :-1] astro_odd = astro[:, :-1] def test_denoise_tv_chambolle_2d(): # astronaut image img = astro_gray.copy() # add noise to astronaut img += 0.5 * img.std() * np.random.rand(*img.shape) # clip noise so that it does not exceed allowed range for float images. img = np.clip(img, 0, 1)
#!/usr/bin/env python # coding: utf-8 # In[1]: from skimage import data, io import numpy as np import matplotlib.pyplot as plt get_ipython().run_line_magic('matplotlib', 'inline') # In[5]: A=data.astronaut() plt.figure(figsize=(8,8)) plt.imshow(A) # In[3]: io.imsave('astronauta_local.png', A) # In[7]: A1=io.imread('astronauta_local.png') plt.imshow(A1)
def main(): image = data.astronaut() image = ia.imresize_single_image(image, (HEIGHT, WIDTH)) kps = [] for y in range(NB_ROWS): ycoord = BB_Y1 + int(y * (BB_Y2 - BB_Y1) / (NB_COLS - 1)) for x in range(NB_COLS): xcoord = BB_X1 + int(x * (BB_X2 - BB_X1) / (NB_ROWS - 1)) kp = (xcoord, ycoord) kps.append(kp) kps = set(kps) kps = [ia.Keypoint(x=xcoord, y=ycoord) for (xcoord, ycoord) in kps] kps = ia.KeypointsOnImage(kps, shape=image.shape) bb = ia.BoundingBox(x1=BB_X1, x2=BB_X2, y1=BB_Y1, y2=BB_Y2) bbs = ia.BoundingBoxesOnImage([bb], shape=image.shape) pairs = [] params = [{ "rotate": 45 }, { "translate_px": 20 }, { "translate_percent": 0.1 }, { "scale": 1.2 }, { "scale": 0.8 }, { "shear": 45 }, { "rotate": 45, "cval": 255 }, { "translate_px": 20, "mode": "constant" }, { "translate_px": 20, "mode": "edge" }, { "translate_px": 20, "mode": "symmetric" }, { "translate_px": 20, "mode": "reflect" }, { "translate_px": 20, "mode": "wrap" }, { "scale": 0.5, "order": 0 }, { "scale": 0.5, "order": 1 }, { "scale": 0.5, "order": 2 }, { "scale": 0.5, "order": 3 }, { "scale": 0.5, "order": 4 }, { "scale": 0.5, "order": 5 }, { "rotate": 45, "translate_px": 20, "scale": 1.2 }, { "rotate": 45, "translate_px": 20, "scale": 0.8 }, { "rotate": (-45, 45), "translate_px": (-20, 20), "scale": (0.8, 1.2), "order": ia.ALL, "mode": ia.ALL, "cval": ia.ALL }, { "rotate": (-45, 45), "translate_px": (-20, 20), "scale": (0.8, 1.2), "order": ia.ALL, "mode": ia.ALL, "cval": ia.ALL }, { "rotate": (-45, 45), "translate_px": (-20, 20), "scale": (0.8, 1.2), "order": ia.ALL, "mode": ia.ALL, "cval": ia.ALL }, { "rotate": (-45, 45), "translate_px": (-20, 20), "scale": (0.8, 1.2), "order": ia.ALL, "mode": ia.ALL, "cval": ia.ALL }] seqs_skimage = [iaa.Affine(backend="skimage", **p) for p in params] seqs_cv2 = [iaa.Affine(backend="auto", **p) for p in params] #seqs_cv2 = [] #for p in params: # seqs_cv2 = [iaa.Affine(backend="cv2", **p) for p in params] for seq_skimage, seq_cv2 in zip(seqs_skimage, seqs_cv2): #seq_skimage.localize_random_state_() #seq_cv2.localize_random_state_() #seq_cv2.copy_random_state_(seq_skimage) seq_skimage_det = seq_skimage.to_deterministic() seq_cv2_det = seq_cv2.to_deterministic() seq_cv2_det.copy_random_state_(seq_skimage_det) image_aug_skimage = seq_skimage_det.augment_image(image) image_aug_cv2 = seq_cv2_det.augment_image(image) #print(image_aug.dtype, np.min(image_aug), np.max(image_aug)) kps_aug_skimage = seq_skimage_det.augment_keypoints([kps])[0] kps_aug_cv2 = seq_cv2_det.augment_keypoints([kps])[0] bbs_aug_skimage = seq_skimage_det.augment_bounding_boxes([bbs])[0] bbs_aug_cv2 = seq_cv2_det.augment_bounding_boxes([bbs])[0] image_before_skimage = np.copy(image) image_before_cv2 = np.copy(image) image_before_skimage = kps.draw_on_image(image_before_skimage) image_before_cv2 = kps.draw_on_image(image_before_cv2) image_before_skimage = bbs.draw_on_image(image_before_skimage) image_before_cv2 = bbs.draw_on_image(image_before_cv2) image_after_skimage = np.copy(image_aug_skimage) image_after_cv2 = np.copy(image_aug_cv2) image_after_skimage = kps_aug_skimage.draw_on_image( image_after_skimage) image_after_cv2 = kps_aug_cv2.draw_on_image(image_after_cv2) image_after_skimage = bbs_aug_skimage.draw_on_image( image_after_skimage) image_after_cv2 = bbs_aug_cv2.draw_on_image(image_after_cv2) pairs.append( np.hstack( (image_before_skimage, image_after_skimage, image_after_cv2))) ia.imshow(np.vstack(pairs)) imageio.imwrite("affine.jpg", np.vstack(pairs))
img = np.clip(img, 0, 255).astype(np.uint8) img = Image.fromarray(img) # grayscale if "grayscale" in cfg: img = transforms.to_grayscale(img, num_output_channels=cfg["grayscale"]) anchor = transforms.to_grayscale( anchor, num_output_channels=cfg["grayscale"]) img = transforms.center_crop(img, 128) return anchor, img if __name__ == "__main__": m = Manipulator("example.yaml") from skimage import data from PIL import Image import matplotlib.pyplot as plt img = Image.fromarray(data.astronaut()) plt.imshow(img) plt.show() anchor, same = m(img) plt.imshow(same) plt.show() plt.imshow(anchor) plt.show()
def test_li_astro_image(): img = skimage.img_as_ubyte(data.astronaut()) assert 66 < threshold_li(img) < 68
def test_astronaut(): """ Test that "astronaut" image can be loaded. """ astronaut = data.astronaut() assert_equal(astronaut.shape, (512, 512, 3))
Algorithms. ICPR 2014, pp 996-1001. DOI:10.1109/ICPR.2014.181 https://www.tu-chemnitz.de/etit/proaut/forschung/rsrc/cws_pSLIC_ICPR.pdf """ from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from skimage.data import astronaut from skimage.color import rgb2gray from skimage.filters import sobel from skimage.segmentation import felzenszwalb, slic, quickshift, watershed from skimage.segmentation import mark_boundaries from skimage.util import img_as_float img = img_as_float(astronaut()[::2, ::2]) segments_fz = felzenszwalb(img, scale=100, sigma=0.5, min_size=50) segments_slic = slic(img, n_segments=250, compactness=10, sigma=1) segments_quick = quickshift(img, kernel_size=3, max_dist=6, ratio=0.5) gradient = sobel(rgb2gray(img)) segments_watershed = watershed(gradient, markers=250, compactness=0.001) print("Felzenszwalb's number of segments: %d" % len(np.unique(segments_fz))) print('SLIC number of segments: %d' % len(np.unique(segments_slic))) print('Quickshift number of segments: %d' % len(np.unique(segments_quick))) fig, ax = plt.subplots(2, 2, sharex=True, sharey=True, subplot_kw={'adjustable': 'box-forced'})
#!/usr/bin/env python # -*- coding:utf-8 -*- from skimage import data from skimage import io import numpy as np import matplotlib.pyplot as plt import pylab image = data.binary_blobs() plt.imshow(image, 'gray') pylab.show() image_color = data.astronaut() plt.imshow(image_color) pylab.show() image_local = io.imread('e:/cf400dc4d7e128635f2e066f7497eb8b.jpg') plt.imshow(image_local) pylab.show()
""" Display a points layer on top of an image layer using the add_points and add_image APIs """ import numpy as np from skimage import data from skimage.color import rgb2gray import napari with napari.gui_qt(): # add the image viewer = napari.view_image(rgb2gray(data.astronaut())) # add the points points = np.array([[100, 100], [200, 200], [333, 111]]) size = np.array([10, 20, 20]) viewer.add_points(points, size=size) # unselect the image layer viewer.layers[0].selected = False # adjust some of the points layer properties layer = viewer.layers[1] # change the layer name layer.name = 'points' # change the layer visibility layer.visible = False layer.visible = True
Vol. 2018, Article ID 3950312 :DOI:`10.1155/2018/3950312` .. [4] C. K. Chui and H. N. Mhaskar, MRA Contextual-Recovery Extension of Smooth Functions on Manifolds, Appl. and Comp. Harmonic Anal., 28 (2010), 104-113, :DOI:`10.1016/j.acha.2009.04.004` """ import numpy as np import matplotlib.pyplot as plt from skimage import data from skimage.morphology import disk, binary_dilation from skimage.restoration import inpaint image_orig = data.astronaut() # Create mask with six block defect regions mask = np.zeros(image_orig.shape[:-1], dtype=bool) mask[20:60, 0:20] = 1 mask[160:180, 70:155] = 1 mask[30:60, 170:195] = 1 mask[-60:-30, 170:195] = 1 mask[-180:-160, 70:155] = 1 mask[-60:-20, 0:20] = 1 # add a few long, narrow defects mask[200:205, -200:] = 1 mask[150:255, 20:23] = 1 mask[365:368, 60:130] = 1