Beispiel #1
0
 def create_noise_dots(image, color, width=3, number=30):
     draw = Draw(image)
     w, h = image.size
     for _ in range(number):
         xx = random.randint(1, width)
         yy = random.randint(1, width)
         x = random.randint(0, w - xx)
         y = random.randint(0, h - yy)
         draw.ellipse(((x, y), (x + xx, y + yy)),
                      fill=color if rand_bool() else random_color())
     return image
Beispiel #2
0
 def create_frame(self, spoke: int = 0, spoke_frame: int = 0) -> PILImage:
     image = Image.new('RGBA', self.size, self.bg)
     draw = Draw(image, 'RGBA')  # type: ImageDraw
     opacity_step_pct = (1 - self.opacity_min_pct) / self.spokes
     a_offset = int(255 * (spoke_frame * self.frame_fade_pct))
     # log.debug(f'Creating frame for focused {spoke=} {spoke_frame=} {opacity_step_pct=} {a_offset=}')
     for i, r, box in self._iter_boxes(spoke):
         a = int(255 * (1 - (i * opacity_step_pct))) - a_offset
         # log.debug(f'    Drawing spoke={i} with {box=} alpha={a} {r=} area={pi * r ** 2:,.2f} px')
         draw.ellipse(box, fill=(*self.rgb, a))
     return image
 def make_mask(self, f):
     im = Image.new("L", (self.hw, self.hw))
     draw_mask = Draw(im)
     box_list = []
     for i, o in enumerate(f.transpose()):
         r = int(o[-1] * self.hw / 2)
         p = [int((x + 1) * self.hw / 2.0) for x in o[1::-1]]
         box = (p[0] - r, p[1] - r, p[0] + r, p[1] + r)
         box_list.append(box)
         if not all(0 <= b <= self.hw for b in box):
             continue
         draw_mask.ellipse(box, fill=i + 1, outline=i + 1)
     return np.array(im), box_list
Beispiel #4
0
    def draw_point(self, latlong):
        if self._image:
            tmp = self._image.copy()
            draw = Draw(tmp)
            pix = MapData.latlng_to_pixel(latlong)

            #            tilepix = (pix[0] - (self._pxcenter[0]-TILESIZE/2), pix[1] - (self._pxcenter[1]-TILESIZE/2))
            tilepix = (pix[0] - self._pxtopleft[0],
                       pix[1] - self._pxtopleft[1])
            draw.ellipse([(tilepix[0] - 5, tilepix[1] - 5),
                          (tilepix[0] + 5, tilepix[1] + 5)],
                         fill=ImageColor.getrgb('red'))
            return tmp
Beispiel #5
0
def make_mask(f, hw):
    im = Image.new("L", (hw, hw))
    draw_mask = Draw(im)
    for i, o in enumerate(f.transpose()):
        if np.linalg.norm(o[:3]) == 0:
            continue
        r = int(o[-1] * hw / 2)
        p = [int((x + 1) * hw / 2.0) for x in o]
        box = (p[0] - r, p[1] - r, p[0] + r, p[1] + r)
        if i < 5:
            draw_mask.ellipse(box, fill=i + 1, outline=i + 1)
        else:
            draw_mask.rectangle(box, fill=i + 1, outline=i + 1)
    return np.array(im)
Beispiel #6
0
def processPoint(arr, coords):
    blank = Image.new('RGB', (len(arr[0]), len(arr)))
    drawer = Draw(blank, 'RGBA')
    elrad = 4
    for i in range(len(coords[0])):
        pointArr = []
        pointArr.append(coords[0][i] - elrad)
        pointArr.append(coords[1][i] - elrad)
        pointArr.append(coords[0][i] + elrad)
        pointArr.append(coords[1][i] + elrad)
        drawer.ellipse(pointArr, (255, 255, 255, 25))
    arr = np.asarray(blank)
    arr = arr[:, :, 0]
    return arr
def draw_circle(x: float, y: float, radius: int, color: int,
                draw_object: ImageDraw.Draw) -> None:
    """

    Args:
        x: x coordinate of center
        y: y coordinate of center
        color: a number from 1 to 10 to represent the color of the circle.
        radius: the radius

    Returns:

    """
    draw_object.ellipse((x - radius, y - radius, x + radius, y + radius),
                        fill=COLOR_DICT[color])
Beispiel #8
0
    def create_noise_circles(image, number):
        w, h = image.size
        while number:
            distance = random.randint(1, 10)
            x1 = random.randint(0, w)
            x2 = x1 + distance
            y1 = random.randint(0, h)
            y2 = y1 + distance

            points = [x1, y1, x2, y2]
            draw = Draw(image)
            color = random_color(10, 200, random.randint(220, 225))
            draw.ellipse(points, fill=color, outline=color)
            number -= 1
        return image
Beispiel #9
0
def fast_paint(image: Image,
               brushes: List[int] = [2, 4, 8, 16, 32],
               blur_factor: int = 2,
               threshold: int = 100) -> Image:
    width, height = image.size
    canvas = Image.new('RGB', image.size, color=(255, 255, 255))
    draw_canvas = Draw(canvas)
    canvas_data = np.array(canvas)

    # Run through each brush size from large to small
    for brush_size in sorted(brushes, reverse=True):
        size_2 = brush_size // 2
        blurred_image = image.filter(GaussianBlur(blur_factor * brush_size))
        blurred_image_data = np.array(blurred_image)
        to_brush_positions = []

        # Run through each image with squares of brush_size width
        for x in range(size_2, width - size_2, brush_size):
            for y in range(size_2, height - size_2, brush_size):
                canvas_data[x - size_2:x + size_2, y - size_2:y + size_2]
                # Calculate the error between points in area
                points_in_area = [(i, j)
                                  for i in range(x - size_2, x + size_2)
                                  for j in range(y - size_2, y + size_2)]
                distances = [(distance_rgb(image(point),
                                           blurred_image.getpixel(point)),
                              point) for point in points_in_area]

                error = sum(score for score, _ in distances)
                print(error)
                if error > threshold:
                    _, max_point = max(distances)
                    to_brush_positions.append({
                        'point':
                        max_point,
                        'color':
                        image.getpixel(max_point)
                    })

        # Paint circles of shuffled brush positions and colors
        shuffle(to_brush_positions)
        for to_paint in to_brush_positions:
            x, y = to_paint['point']
            left_up = (x - size_2, y - size_2)
            right_down = (x + size_2, y + size_2)
            draw_canvas.ellipse([left_up, right_down], fill=to_paint['color'])

    return canvas
    def draw(self, image_to_draw_on):
        drawing_context = Draw(image_to_draw_on)
        if self.bounding_box:
            coords = Shape.scale_float_coords_to_image_size(self.bounding_box, image_to_draw_on)
        else:
            coords = Shape.scale_float_coords_to_image_size(self.vertices, image_to_draw_on)

        if self.kind == "chord":
            drawing_context.chord(coords, self.start_angle, self.end_angle, fill=self.color)
        elif self.kind == "ellipse":
            drawing_context.ellipse(coords, fill=self.color)
        elif self.kind == "pieslice":
            drawing_context.pieslice(coords, self.start_angle, self.end_angle, fill=self.color)
        elif self.kind == "polygon":
            drawing_context.polygon(coords, fill=self.color)
        else:
            raise Exception("unsupported kind")
Beispiel #11
0
def drawPointObjects(im, data, **kwargs):
    if ('drawIm' in kwargs): drawIm = kwargs['drawIm']
    else: drawIm = Draw(im)

    if ('fillColor' in kwargs): fillColor = kwargs['fillColor']
    else: fillColor = 'red'

    if ('elrad' in kwargs): fillColor = kwargs['elrad']
    else: elrad = 3

    coords = data
    for i in range(len(coords[0])):
        pointArr = []
        pointArr.append(coords[0][i] - elrad)
        pointArr.append(coords[1][i] - elrad)
        pointArr.append(coords[0][i] + elrad)
        pointArr.append(coords[1][i] + elrad)
        drawIm.ellipse(pointArr, fill=fillColor)
    return im
def visualize_sift_descriptors(img, *, n=100):
    """
    Visualize the image with the sift descriptors.
    """
    from PIL import Image
    from PIL.ImageDraw import Draw
    image = Image.fromarray(img)
    draw = Draw(image)

    descriptors_magnitude = {
        coords: np.sum(descriptor)
        for coords, descriptor in create_sift_descriptors(img).items()
    }
    sorted_descriptors = sorted(descriptors_magnitude.items(),
                                key=operator.itemgetter(1))

    for ((x, y), _) in sorted_descriptors[-n:]:
        draw.ellipse([(x - 2, y - 2), (x + 2, y + 2)], fill='red')
    return image
Beispiel #13
0
def draw_balloon(img_draw: ImageDraw.Draw, points: Box, fill=None, width=0):
    r_x0 = points.top_left.x
    r_y0 = points.top_left.y + BOX_RADIUS
    r_x1 = points.bottom_right.x
    r_y1 = points.bottom_right.y - BOX_RADIUS
    img_draw.rectangle([r_x0, r_y0, r_x1, r_y1], fill=fill, width=width)
    r_x0 = points.top_left.x + BOX_RADIUS
    r_y0 = points.top_left.y
    r_x1 = points.bottom_right.x - BOX_RADIUS
    r_y1 = points.bottom_right.y
    img_draw.rectangle([r_x0, r_y0, r_x1, r_y1], fill=fill, width=width)
    diam = 2 * BOX_RADIUS
    c_x0 = points.top_left.x
    c_y0 = points.top_left.y
    c_x1 = c_x0 + diam
    c_y1 = c_y0 + diam
    img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width)
    c_x0 = points.bottom_right.x - diam
    c_x1 = c_x0 + diam
    img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width)
    c_y0 = points.bottom_right.y - diam
    c_y1 = c_y0 + diam
    img_draw.ellipse([c_x0, c_y0, c_x1, c_y1], fill=fill, width=width)

    arrow_x = 10
    arrow_y = 10 if BOX_RADIUS < 10 else BOX_RADIUS
    arrow = [
        (points.top_left.x - arrow_x, points.bottom_right.y),
        (points.top_left.x, points.bottom_right.y - arrow_y),
        (points.top_left.x + diam, points.bottom_right.y - arrow_y),
        (points.top_left.x + diam, points.bottom_right.y),
    ]
    img_draw.polygon(arrow, fill=fill)
Beispiel #14
0
def generate_captcha(directory="tmp", letters=ascii_uppercase+digits,
        length=3, font_size=30, lines=5, mode="ellipse", font="FreeSerif.ttf"):
    """ Returns a tuple : (path, code) """
    dimensions = ((length + 1) * font_size, int(font_size * 2))
    path = "%s%s" % (os.path.join(directory, "".join(choice(ascii_letters) for
        i in xrange(7))), ".png")
    code = "".join(choice(letters) for i in range(length))
    background_color = tuple( [randrange(190, 230) for i in xrange(3)] )
    master = new_image("RGB", dimensions, background_color)

    # On colle les lettres
    for i, l in enumerate(code):
        img, mask = generate_letter(l, font_size, font)
        for _ in xrange(3):
            # On colle plusieurs fois pour plus de netteté
            master.paste(img, (font_size / 2 + font_size * i , font_size / 3),
                    mask)

    # Et on dessine quelques jolies lignes
    draw = Draw(master)
    for i in xrange(lines):
        color = tuple( [randrange(128, 190) for i in xrange(3)] )
        #pen = Pen("black", opacity=64)
        #pen.color = color
        w = dimensions[0]
        h = dimensions[1]
        geom = (randrange(0, int(w * 3. / 4)), randrange(0, h),
                randrange(int(w * 1. / 4), w), randrange(0, h))
        if mode == "mixed":
            mode_ = choice( ("ellipse", "line") )
        else:
            mode_ = mode
        if mode_ == "ellipse":
            draw.ellipse(geom, None, color)
        else:
            draw.line(geom, color, 1)
    with open(path, "w") as f:
        master.save(f)
    return (path, code)
Beispiel #15
0
    def paint(self, draw: ImageDraw.Draw, regions: RegionMap) -> None:
        angle = radians(180.0 - 30)  # 30 degrees
        c, s = cos(angle), sin(angle)
        d = self.p1[0] - self.p0[0], self.p1[1] - self.p0[1]
        left = d[0] * c - d[1] * s, d[0] * s + d[1] * c
        right = d[0] * c + d[1] * s, -d[0] * s + d[1] * c
        lf = self.size / (d[0]**2 + d[1]**2)**0.5

        # Draw arrow shaft
        draw.line([self.p0, self.p1], fill=self.color, width=self.width)
        # Draw dot
        draw.ellipse(
            (self.p1[0] - 5, self.p1[1] - 5, self.p1[0] + 5, self.p1[1] + 5),
            fill=self.color)
        # Draw left arrow wing
        draw.line(
            [(self.p1[0] + lf * left[0], self.p1[1] + lf * left[1]), self.p1],
            fill=self.color,
            width=self.width)
        # Draw right arrow wing
        draw.line([(self.p1[0] + lf * right[0], self.p1[1] + lf * right[1]),
                   self.p1],
                  fill=self.color,
                  width=self.width)
Beispiel #16
0
        detected_faces = detect_faces(img)
        #crop the detected face
        img = Image.fromarray(img).crop(detected_faces[0])

        #color quantization
        quantized_image = color_quant(img)

        face = Image.fromarray(quantized_image)
        median = ImageStat.Stat(face).median

        #to convert BGR to RGB
        org_img = image[:, :, ::-1].copy()
        #draw an ellipse with fill color as the detected skin color
        out = Image.fromarray(org_img)
        d = Draw(out)
        d.ellipse(((0, 0), (0.2 * image.shape[0], 0.2 * image.shape[1])),
                  fill=tuple(median))

        #output the results
        #plt.imshow(res2)
        #plt.show()
        #plt.imshow(out)
        #plt.axis('off')
        #plt.show()
        success += 1
        out.save('../results/out3/out_file_' + str(success) + '.jpg')
        print('Success ' + str(success))

    except:
        fail += 1
        print('Fail ' + str(fail))
make_sure_path_exists(overlay_path)

# Superimpose smoothed midlines on the (cropped) original image sequence
for i in range(Nf):
    shift = -offsets[i]
#    im = Image.open(original_images.format(i+1))
#    im = im.crop((0, 680, 2260, 680+810)) 
    im = open_png(sillhouette_path.format(i+1))
    im = Image.fromarray(im.astype(np.uint8)).convert('RGB')
    d = Draw(im)
    y = smid[:,i].astype(int)+shift[1]
    x = (np.arange(smid.shape[0])*end[i]/float(smid.shape[0]-1)).astype(int)+shift[0]
    d.line(zip(x,y), fill=(255,0,0), width=3 )
    tp = tip_locations[i]
    d.ellipse((tp[0]-1, tp[1]-1, tp[0]+1, tp[1]+1), fill=(0,0,255))
    im.save(overlay_path+'orig_{}.png'.format(i))


# Calculate scaling between transformed and y-coordinate
# in pixels - dy/di
sc = end / float(smid.shape[0]-1)

# Evaluate derivatives of the smoothed midline - dx/dy and d^2 x / dy^2
# Use scaling factor to give in terms of pixel coordinates
d = u(range(new_mid.shape[0]), range(new_mid.shape[1]), dx=1)/sc
dd = u(range(new_mid.shape[0]), range(new_mid.shape[1]), dx=2)/sc/sc


# Calculate distance 
# ds = ds / di. Use d^2 d/dy^2 = 1 + (dx/dy)^2 and dy/di = sc 
def image_crop(
    image: Union[bytes, Image],
    crop: Optional[Crop] = None,
    width_preview: Optional[int] = None,
    image_alt: Optional[str] = None,
    min_width: Optional[int] = None,
    min_height: Optional[int] = None,
    max_width: Optional[int] = None,
    max_height: Optional[int] = None,
    # FIXME: Changing these properties, the component is rerendered unfortunately.
    # ----
    # keep_selection: Optional[bool] = None,
    # disabled: Optional[bool] = None,
    # locked: Optional[bool] = None,
    rule_of_thirds: Optional[bool] = None,
    circular_crop: Optional[bool] = None,
    # ----
    key: Optional[str] = None,
) -> Optional[Image]:
    import dataclasses
    from io import BytesIO
    from os import path

    import streamlit as st
    from PIL.Image import composite as composite_image
    from PIL.Image import new as new_image
    from PIL.Image import open as open_image
    from PIL.ImageDraw import Draw
    from streamlit.components import v1 as components
    from streamlit.elements.image import image_to_url

    global _impl

    if _impl is None:
        if _DEBUG:
            option_address = st.get_option("browser.serverAddress")
            option_port = st.get_option("browser.serverPort")
            _impl = (
                components.declare_component(
                    "image_crop",
                    url="http://localhost:3001",
                ),
                lambda s: f"http://{option_address}:{option_port}" + s,
            )
        else:
            _impl = (
                components.declare_component(
                    "image_crop",
                    path=path.join(path.dirname(path.abspath(__file__)),
                                   "frontend/build"),
                ),
                lambda s: s,
            )

    if isinstance(image, Image):
        image_ = image
    else:
        image_ = open_image(BytesIO(image))

    width, _ = image_.size

    src = image_to_url(
        image_,
        width=min(width, width_preview) if width_preview else width,
        clamp=False,
        channels="RGB",
        output_format="auto",
        image_id="foo",
    )

    crop_ = None if crop is None else dataclasses.asdict(crop)

    default = {
        "width": 0.0,
        "height": 0.0,
        "x": 0.0,
        "y": 0.0,
    }

    component, build_url = _impl

    result = component(
        src=build_url(src),
        image_alt=image_alt,
        minWidth=min_width,
        minHeight=min_height,
        maxWidth=max_width,
        maxHeight=max_height,
        # FIXME: Changing these properties, the component is rerendered unfortunately.
        # ----
        keepSelection=None,
        disabled=None,
        locked=None,
        ruleOfThirds=rule_of_thirds,
        circularCrop=circular_crop,
        # ----
        crop=crop_,
        key=key,
        default=default,
    )

    w, h = image_.size

    w_crop = int(w * float(result["width"]) / 100)
    h_crop = int(h * float(result["height"]) / 100)
    x0 = int(w * float(result["x"]) / 100)
    y0 = int(h * float(result["y"]) / 100)
    x1 = x0 + w_crop
    y1 = y0 + h_crop

    if w_crop <= 0 or h_crop <= 0:
        return None
    else:
        image_crop = image_.crop((x0, y0, x1, y1))
        if circular_crop:
            background = new_image("RGBA", (w_crop, h_crop), (0, 0, 0, 0))
            mask = new_image("L", (w_crop, h_crop), 0)
            draw = Draw(mask)
            draw.ellipse((0, 0, w_crop, h_crop), fill="white")
            image_crop = composite_image(image_crop, background, mask)

        return image_crop