Beispiel #1
0
def test_throws_when_intensity_range_out_of_range():
    with testing.raises(ValueError):
        random_shapes((1000, 1234), max_shapes=1, multichannel=False,
                      intensity_range=(0, 256))
    with testing.raises(ValueError):
        random_shapes((2, 2), max_shapes=1,
                      intensity_range=((-1, 255),))
def gen_image(imgType, noise=True):
    if imgType == 'grayscale':
        img, _ = random_shapes((512, 512),
                               max_shapes=30,
                               intensity_range=(0, 255),
                               min_size=50,
                               multichannel=False,
                               max_size=np.random.randint(50, 150),
                               allow_overlap=False)
    else:
        img, _ = random_shapes((512, 512),
                               max_shapes=30,
                               intensity_range=(0, 255),
                               min_size=50,
                               multichannel=False,
                               max_size=np.random.randint(50, 150),
                               allow_overlap=False)
    img[img == 255] = 0
    mask = np.zeros(img.shape, dtype=np.uint8)
    mask[:, :] = img
    mask[mask > 0] = 255

    if noise:
        nsImg = random_noise(img)
    return nsImg, mask
Beispiel #3
0
def test_generate_triangle_throws_when_size_too_small():
    with testing.raises(ValueError):
        random_shapes((128, 64),
                      max_shapes=1,
                      min_size=1,
                      max_size=1,
                      shape='triangle')
def test_throws_when_intensity_range_out_of_range():
    with testing.raises(ValueError):
        random_shapes((1000, 1234), max_shapes=1, multichannel=False,
                      intensity_range=(0, 256))
    with testing.raises(ValueError):
        random_shapes((2, 2), max_shapes=1,
                      intensity_range=((-1, 255),))
Beispiel #5
0
def test_generate_circle_throws_when_size_too_small():
    with testing.raises(ValueError):
        random_shapes((64, 128),
                      max_shapes=1,
                      min_size=1,
                      max_size=1,
                      shape='circle')
def test_throws_when_intensity_range_out_of_range():
    with testing.raises(ValueError):
        with expected_warnings(["`multichannel` is a deprecated argument"]):
            random_shapes((1000, 1234),
                          max_shapes=1,
                          multichannel=False,
                          intensity_range=(0, 256))
    with testing.raises(ValueError):
        random_shapes((2, 2), max_shapes=1, intensity_range=((-1, 255), ))
def test_generates_gray_images_with_correct_shape_deprecated_multichannel():
    with expected_warnings(["`multichannel` is a deprecated argument"]):
        image, _ = random_shapes((4567, 123),
                                 min_shapes=3,
                                 max_shapes=20,
                                 multichannel=False)
    assert image.shape == (4567, 123)

    # repeat prior test, but check for positional multichannel warning
    with expected_warnings(["Providing the `multichannel` argument"]):
        image, _ = random_shapes((4567, 123), 20, 3, 2, None, False)
    assert image.shape == (4567, 123)
Beispiel #8
0
def random_shape_maze(width,
                      height,
                      max_shapes,
                      max_size,
                      allow_overlap,
                      shape=None,
                      seed=None):
    x, _ = random_shapes([height, width],
                         max_shapes,
                         max_size=max_size,
                         multichannel=False,
                         shape=shape,
                         allow_overlap=allow_overlap,
                         random_seed=seed)

    x[x == 255] = 0
    x[np.nonzero(x)] = 1

    # wall
    x[0, :] = 1
    x[-1, :] = 1
    x[:, 0] = 1
    x[:, -1] = 1

    return np.asarray(x, dtype=np.float32)
Beispiel #9
0
def test_returns_empty_labels_and_white_image_when_cannot_fit_shape():
    # The circle will never fit this.
    with expected_warnings(['Could not fit']):
        image, labels = random_shapes(
            (10000, 10000), max_shapes=1, min_size=10000, shape='circle')
    assert len(labels) == 0
    assert (image == 255).all()
Beispiel #10
0
def WorldG():
    image2, _ = random_shapes((128, 128),
                              shape='circle',
                              min_shapes=10,
                              max_shapes=15,
                              min_size=20,
                              max_size=25,
                              intensity_range=((100, 254), ))

    image2 = np.where(image2 == 255, 0, image2)
    x_1 = np.random.randint(0, 120)
    y_1 = np.random.randint(0, 120)
    x_2 = np.random.randint(0, 120)
    y_2 = np.random.randint(0, 120)
    while distance(x_1, x_2, y_1, y_2) < 50:
        x_1 = np.random.randint(0, 120)
        y_1 = np.random.randint(0, 120)
        x_2 = np.random.randint(0, 120)
        y_2 = np.random.randint(0, 120)

    cv2.circle(image2, (x_1, y_1), 5, (255, 255, 255), thickness=cv2.FILLED)
    cv2.circle(image2, (x_2, y_2), 5, (255, 255, 255), thickness=cv2.FILLED)
    cv2.imwrite('test.png', image2)

    #plt.imshow(image2)
    #plt.title('my picture1')
    #plt.show()
    return image2
Beispiel #11
0
def test_generates_white_image_when_min_pixel_intensity_255():
    image, labels = random_shapes((128, 128),
                                  max_shapes=3,
                                  min_pixel_intensity=255,
                                  random_seed=42)
    assert len(labels) > 0
    assert (image == 255).all()
 def flow_random_shapes(self, ):
     while True:
         images = np.empty(self.im_shape)
         kspaces = np.empty(self.im_shape)
         for i in range(self.batch_size):
             image, _ = random_shapes(
                 (self.size, self.size),
                 max_shapes=self.n_shapes,
                 multichannel=False,
                 allow_overlap=True,
                 max_size=self.size,
             )
             image = image.astype('float32')
             image /= 255
             kspace = fft(image)
             images[i, ..., 0] = image
             kspaces[i, ..., 0] = kspace
         mask = gen_mask(kspaces[0, ..., 0], accel_factor=self.af)
         fourier_mask = np.repeat(mask.astype(np.float), self.size, axis=0)
         mask_batch = np.repeat(fourier_mask[None, ...],
                                len(kspaces),
                                axis=0)[..., None]
         kspaces *= mask_batch
         mask_batch = mask_batch[..., 0]
         yield (kspaces, mask_batch), images
def random_mask(H, W, mask_size=200):
    """
    mask: ranges in [0,1]
    """
    masked_image = np.zeros([H, W, 3])
    mask = random_shapes(
        [H, W],
        max_shapes=1,
        min_shapes=1,
        max_size=mask_size,
        min_size=mask_size / 2,
        multichannel=False,
        intensity_range=[0, 0],
    )[0]
    mask = np.stack((mask, mask, mask), axis=-1)
    random_state = np.random.RandomState(None)
    distortion_range = 50
    alpha = np.random.rand() * 6
    forward_dx = (
        gaussian_filter((random_state.rand(H, W) * 2 - 1), distortion_range, mode="constant", cval=0) * alpha * 1000
    )
    forward_dy = (
        gaussian_filter((random_state.rand(H, W) * 2 - 1), distortion_range, mode="constant", cval=0) * alpha * 1000
    )
    mask = forward_mapping(mask, forward_dy, forward_dx, maxIter=3, precision=1e-3) / 255
    mask = 1 - gaussian(mask, sigma=0, preserve_range=True, multichannel=False, anti_aliasing=True)
    mask = mask[:, :, 0]

    return mask
def test_returns_empty_labels_and_white_image_when_cannot_fit_shape():
    # The circle will never fit this.
    with expected_warnings(['Could not fit']):
        image, labels = random_shapes(
            (10000, 10000), max_shapes=1, min_size=10000, shape='circle')
    assert len(labels) == 0
    assert (image == 255).all()
Beispiel #15
0
def generate_rect_mask(mesh, min_shapes=1, max_shapes=1, skimage_labels=False, multichannel=False, intensity_range=((1, 1)), units=False, shape='rectangle',**kargs):
    image, labels = random_shapes(mesh.shape, min_shapes=min_shapes, shape='rectangle', max_shapes=max_shapes, multichannel=multichannel, intensity_range=intensity_range, **kargs)
    idx = image == 255
    image[idx] = 0
    if not skimage_labels:
        labels = convert_labels(labels, mesh, units=units)
    return image, labels
Beispiel #16
0
def gen_one_image(h=64, w=64):

    shapes = ('rectangle', 'triangle', 'circle')
    n_images = 3  #np.random.randint(1, 9)
    matrix = np.zeros((h, w, n_images))
    image = np.zeros((h, w, 3))
    mask = np.full((h, w), -1)
    for i in range(n_images):
        n_shape = np.random.randint(len(shapes))
        tmp_image, _ = random_shapes(
            (h, w),
            max_shapes=1,
            min_shapes=1,
            shape=shapes[n_shape],
            #   multichannel=True, num_channels=3,
            min_size=11,
            max_size=22,
            allow_overlap=True)
        matrix[tmp_image[:, :, 0] < 255, i] = 1
        mask[tmp_image[:, :, 0] < 255] = n_shape
        tmp_image[tmp_image == 255] = 0

        image[tmp_image[:, :, 0] > 0] = tmp_image[tmp_image[:, :, 0] > 0]
    image /= 255
    image[image == 0] = 1

    return image, mask, matrix
Beispiel #17
0
def test_random_shapes_is_reproducible_with_seed():
    random_seed = 42
    labels = []
    for _ in range(5):
        _, l = random_shapes((128, 128), max_shapes=5, random_seed=random_seed)
        labels.append(l)
    assert all(other == labels[0] for other in labels[1:])
Beispiel #18
0
    def _apply_shapes(self, data: np.ndarray) -> np.ndarray:
        channels, height, width = get_image_dims(data)
        # Wrap intensity_range in another tuple for color images. User might have provided nested tuple already though,
        #  so don't wrap those again.
        intensity_range = self.intensity_range
        if channels > 1 and not isinstance(intensity_range[0], tuple):
            intensity_range = (intensity_range, )
        shapes, _ = random_shapes(image_shape=(height, width),
                                  max_shapes=self.max_shapes,
                                  max_size=self.max_size,
                                  num_channels=channels,
                                  intensity_range=intensity_range,
                                  allow_overlap=True)
        alpha = np.random.uniform(self.transparency_range[0],
                                  self.transparency_range[1])

        # Convert shapes to range [0,1] if image is floating point
        normalized_shapes = shapes / 255.0 if np.issubdtype(
            data.dtype, np.floating) else shapes

        blend = normalized_shapes * alpha + data * (1.0 - alpha)

        # Combine images without whitening non-shape regions
        overlay = np.where(shapes < 255, blend, data)

        return overlay.astype(data.dtype)
Beispiel #19
0
def test_generates_white_image_when_intensity_range_255():
    image, labels = random_shapes((128, 128),
                                  max_shapes=3,
                                  intensity_range=((255, 255), ),
                                  random_seed=42)
    assert len(labels) > 0
    assert (image == 255).all()
Beispiel #20
0
def make_image():
    i = np.random.randint(0,255,(200,256,4),dtype='uint8')
    i[:,:,3] = 0
    shape = random_shapes((200, 256), max_shapes=4,allow_overlap=True,
                  intensity_range=((100, 255)),num_channels=1)
    shape = shape[0].reshape((200,256))
    i[:,:,3][shape[:]<255] =255
    return i
Beispiel #21
0
def generate_shapes(img_size):
    img_array, labels = random_shapes(img_size,
                                      min_shapes=2,
                                      max_shapes=10,
                                      multichannel=False,
                                      allow_overlap=True)
    img = Image.fromarray(img_array)
    return img
def test_random_shapes_is_reproducible_with_seed():
    random_seed = 42
    labels = []
    for _ in range(5):
        _, label = random_shapes((128, 128), max_shapes=5,
                                 random_seed=random_seed)
        labels.append(label)
    assert all(other == labels[0] for other in labels[1:])
Beispiel #23
0
def create_simple_object_detection_dataset(path,
                                           n_samples=100,
                                           n_objects_max=3,
                                           n_objects_min=1,
                                           size=(150, 150),
                                           min_size=0.2):
    (path / 'images').mkdir(parents=True, exist_ok=True)
    (path / 'class_images').mkdir(parents=True, exist_ok=True)

    min_dimension = size[0]
    if (size[1] < size[0]):
        min_dimension = size[1]

    # create class labels
    cname = ['red', 'green', 'blue']
    color = [(255, 0, 0), (0, 255, 0), (0, 0, 255)]
    for clr, name in zip(color, cname):
        img_name = f'{name}'
        img = np.ones((50, 50, 3), dtype=np.uint8)
        draw_rectangle(img, start=(0, 0), dimensions=(50, 50), color=clr)
        save_img(path / 'class_images', img_name, img)

    type_shapes = ['rectangle', 'circle', 'ellipse']
    # create images + annotations
    annotations = {}
    images = {}
    for i in range(n_samples):
        labels = []
        bboxs = []
        img_name = f'img_{i}'

        image, shapes = random_shapes(size,
                                      n_objects_max,
                                      multichannel=True,
                                      shape=type_shapes[randint(0, 2)],
                                      min_shapes=n_objects_min,
                                      min_size=min_size * min_dimension)

        for shape in shapes:
            shape_name = shape[0]
            rr_0, rr_1 = shape[1][0]
            cc_0, cc_1 = shape[1][1]
            middle_x = int((rr_0 + rr_1) / 2)
            middle_y = int((cc_0 + cc_1) / 2)

            label = (image[middle_x, middle_y].tolist(), shape_name)
            bbox = (int(cc_0), int(rr_0), int(cc_1), int(rr_1))
            labels.append(label)
            bboxs.append(bbox)

        img_file = img_name + ".jpg"
        images[img_file] = image
        save_img(path / 'images', img_name, image)
        annotations[img_file] = {'labels': labels, 'bboxs': bboxs}

    save_img_annotations(path, annotations)
    return (images, annotations)
Beispiel #24
0
def generateRandShapes(min_s, max_s, min_size, overlap, sizes=(1000, 1000)):
    image, _ = random_shapes(sizes,
                             min_shapes=min_s,
                             max_shapes=max_s,
                             min_size=min_size,
                             allow_overlap=overlap,
                             num_trials=100)

    return image
 def __generate_random_shapes(self, min_shapes, max_shapes):
     img, _ = random_shapes(self.shape,
                            max_shapes,
                            min_shapes=min_shapes,
                            multichannel=False,
                            allow_overlap=True,
                            random_seed=np.random.randint(2**32 - 1))
     # Numpy random usage for random seed unifies random seed which can be set for repeatability
     attempt = np.array(img != 255, dtype=bool)
     return attempt, np.sum(attempt)
Beispiel #26
0
def test_can_generate_one_by_one_rectangle():
    image, labels = random_shapes((50, 128),
                                  max_shapes=1,
                                  min_size=1,
                                  max_size=1,
                                  shape='rectangle',
                                  min_pixel_intensity=1)
    assert len(labels) == 1
    _, bbox = labels[0]
    crop = image[bbox[0][0]:bbox[0][1], bbox[1][0]:bbox[1][1]]
    assert (crop < 255).sum() == 3  # rgb
Beispiel #27
0
def test_can_generate_one_by_one_rectangle():
    image, labels = random_shapes((50, 128),
                                  max_shapes=1,
                                  min_size=1,
                                  max_size=1,
                                  shape='rectangle')
    assert len(labels) == 1
    _, bbox = labels[0]
    crop = image[bbox[0][0]:bbox[0][1], bbox[1][0]:bbox[1][1]]

    # rgb
    assert (np.shape(crop) == (1, 1, 3) and np.any(crop >= 1)
            and np.any(crop < 255))
Beispiel #28
0
def _create_label_data():
    y_true, _ = random_shapes(image_shape=(200, 200),
                              min_shapes=20,
                              max_shapes=30,
                              min_size=10,
                              multichannel=False)
    y_true[y_true == 255] = 0
    y_true, _, _ = relabel_sequential(y_true)

    y_pred = np.zeros_like(y_true)
    y_pred[3:, 3:] = y_true[:-3, :-3]

    return y_true, y_pred
Beispiel #29
0
def get_results(shapes, camera_images, num):
    result = random_shapes((120, 1920),
                           intensity_range=(0, 1),
                           max_shapes=1,
                           min_size=99,
                           max_size=100,
                           shape=shapes,
                           multichannel=False)
    result_pad = np.pad(result[0], ((480, 480), (0, 0)),
                        mode='constant',
                        constant_values=255)
    camera_images.append(result_pad)
    append_single(camera_images, int(num - 1))
def generate_shape():
	for i in range (500):
		image_name = "shape_" + str(i) + ".png"
		#create shape image with color
		shape, _ = random_shapes((256,256), min_shapes=5, max_shapes=10, min_size=20, allow_overlap=True)
		shape_img = Image.fromarray(shape)
		shape_img.save("shape_color/"+image_name,"PNG")

		#create mask
		mask_img = shape_img.convert("L")
		mask_array = np.asarray(mask_img)
		mask_array = np.where(mask_array < 255, 0,255)
		mask_img = Image.fromarray(mask_array.astype(np.uint8))
		mask_img.save("shape_mask/"+image_name,"PNG")
def test_can_generate_one_by_one_rectangle():
    image, labels = random_shapes(
        (50, 128),
        max_shapes=1,
        min_size=1,
        max_size=1,
        shape='rectangle')
    assert len(labels) == 1
    _, bbox = labels[0]
    crop = image[bbox[0][0]:bbox[0][1], bbox[1][0]:bbox[1][1]]

    # rgb
    assert (np.shape(crop) == (1, 1, 3) and np.any(crop >= 1)
            and np.any(crop < 255))
Beispiel #32
0
 def generate_level(self):
     level_setup = random_shapes(
         image_shape=settings.BRICKS_DIMENSION,
         min_shapes=10,
         max_shapes=20,
         min_size=3,
         max_size=10,
         allow_overlap=True,
         intensity_range=((30, 255),))[0]
     for x in range(settings.BRICKS_DIMENSION[0]):
         for y in range(settings.BRICKS_DIMENSION[1]):
             if all(color != 255 for color in level_setup[x][y]):
                 position = pygame.Vector2(board_left() + settings.BRICKS_POSITION[0] + x * settings.BRICK_SIZE[0],
                                           board_top() + settings.BRICKS_POSITION[1] + y * settings.BRICK_SIZE[1])
                 self.bricks.add(Brick(self.screen, position, level_setup[x][y]))
def test_generated_shape_for_channel_axis(channel_axis):
    shape = (128, 64)
    num_channels = 5

    image, _ = random_shapes(shape,
                             num_channels=num_channels,
                             min_shapes=3,
                             max_shapes=10,
                             channel_axis=channel_axis)

    if channel_axis is None:
        expected_shape = shape
    else:
        expected_shape = tuple(np.insert(shape, channel_axis, num_channels))

    assert image.shape == expected_shape
def random_mask(image, mask, num_mask=20, min_size=5, max_size=128):
    """ 
    """
    raw, _ = random_shapes(image.shape[:2],
                           num_mask,
                           min_shapes=2,
                           min_size=min_size,
                           max_size=max_size,
                           multichannel=False,
                           allow_overlap=True)

    mask_raw = 1 - raw / 255.
    noise = np.random.random(image.shape)
    image[mask_raw > 0] = noise[mask_raw > 0] * random.randint(0, 255)

    mask = mask * (mask_raw == 0)
    return image, mask
def test_generates_correct_bounding_boxes_for_triangles():
    image, labels = random_shapes(
        (128, 128),
        max_shapes=1,
        shape='triangle',
        random_seed=42)
    assert len(labels) == 1
    label, bbox = labels[0]
    assert label == 'triangle', label

    crop = image[bbox[0][0]:bbox[0][1], bbox[1][0]:bbox[1][1]]

    # The crop is filled.
    assert (crop >= 0).any() and (crop < 255).any()

    # The crop is complete.
    image[bbox[0][0]:bbox[0][1], bbox[1][0]:bbox[1][1]] = 255
    assert (image == 255).all()
def test_generate_triangle_throws_when_size_too_small():
    with testing.raises(ValueError):
        random_shapes(
            (128, 64), max_shapes=1, min_size=1, max_size=1, shape='triangle')
def test_generate_circle_throws_when_size_too_small():
    with testing.raises(ValueError):
        random_shapes(
            (64, 128), max_shapes=1, min_size=1, max_size=1, shape='circle')
def test_generates_color_images_with_correct_shape():
    image, _ = random_shapes((128, 128), max_shapes=10)
    assert image.shape == (128, 128, 3)
def test_generates_white_image_when_intensity_range_255():
    image, labels = random_shapes((128, 128), max_shapes=3,
                                  intensity_range=((255, 255),),
                                  random_seed=42)
    assert len(labels) > 0
    assert (image == 255).all()
def test_generates_gray_images_with_correct_shape():
    image, _ = random_shapes(
        (4567, 123), min_shapes=3, max_shapes=20, multichannel=False)
    assert image.shape == (4567, 123)
"""
=============
Random Shapes
=============

Example of generating random shapes with particular properties.
"""

import matplotlib.pyplot as plt

from skimage.draw import random_shapes

# Let's start simple and generate a 128x128 image
# with a single grayscale rectangle.
result = random_shapes((128, 128), max_shapes=1, shape='rectangle',
                       multichannel=False)

# We get back a tuple consisting of (1) the image with the generated shapes
# and (2) a list of label tuples with the kind of shape (e.g. circle,
# rectangle) and ((r0, r1), (c0, c1)) coordinates.
image, labels = result
print('Image shape: {}\nLabels: {}'.format(image.shape, labels))

# We can visualize the images.
fig, axes = plt.subplots(nrows=2, ncols=3)
ax = axes.ravel()
ax[0].imshow(image, cmap='gray')
ax[0].set_title('Grayscale shape')

# The generated images can be much more complex. For example, let's try many
# shapes of any color. If we want the colors to be particularly light, we can