Python skimage 模块,color() 实例源码

我们从Python开源项目中,提取了以下22个代码示例,用于说明如何使用skimage.color()

项目:fcn    作者:wkentaro    | 项目源码 | 文件源码
def get_label_colortable(n_labels, shape):
    if cv2 is None:
        raise RuntimeError('get_label_colortable requires OpenCV (cv2)')
    rows, cols = shape
    if rows * cols < n_labels:
        raise ValueError
    cmap = label_colormap(n_labels)
    table = np.zeros((rows * cols, 50, 50, 3), dtype=np.uint8)
    for lbl_id, color in enumerate(cmap):
        color_uint8 = (color * 255).astype(np.uint8)
        table[lbl_id, :, :] = color_uint8
        text = '{:<2}'.format(lbl_id)
        cv2.putText(table[lbl_id], text, (5, 35),
                    cv2.cv.CV_FONT_HERSHEY_SIMPLEX, 0.8, (255, 255, 255), 3)
    table = table.reshape(rows, cols, 50, 50, 3)
    table = table.transpose(0, 2, 1, 3, 4)
    table = table.reshape(rows * 50, cols * 50, 3)
    return table


# -----------------------------------------------------------------------------
# Evaluation
# -----------------------------------------------------------------------------
项目:vsi_common    作者:VisionSystemsInc    | 项目源码 | 文件源码
def overlay_heatmap(image, heatmap, cmap='jet', vmin=0, vmax=1, img_ratio=0.4):
  """ create a visualization of the image with overlaid heatmap """
  img_gray = image
  if len(image.shape) == 3:
    img_gray = skimage.color.rgb2gray(image)
  elif len(image.shape) != 2:
    raise Exception('Image should be grayscale or rgb')

  heatmap_norm = (heatmap - vmin) / (vmax - vmin)
  cmap = mpl.cm.get_cmap(cmap)
  heatmap_vis = cmap(heatmap_norm)
  img_gray_3plane = np.repeat(img_gray.reshape(np.append(img_gray.shape, 1)), 3, axis=2)
  heatmap_overlay = (1.0 - img_ratio) * heatmap_vis[:,:,0:3] + img_ratio * img_gray_3plane
  mask = np.isnan(heatmap)
  heatmap_overlay[mask] = img_gray_3plane[mask]

  return heatmap_overlay
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_circle(x, y, r, img, color_r, color_g, color_b):
    """Draws a Pacman to img

    Args:
        x, int, x location in img
        y, int, y location in img
        r, int, radius of circle
        img, np.array, 3D color image matrix
        color_r, int, red channel of color
        color_g, int, green channel of color
        color_b, int, blue channel of color
    """

    y_start = int(max(0, y - r))
    y_stop = int(min(y + r, img.shape[0] - 1))

    for y_i in range(y_start, y_stop):
        x_start = int(x - math.sqrt(r**2 - (y - y_i)**2))
        x_stop = int(x + math.sqrt(r**2 - (y - y_i)**2))

        for x_i in range(x_start, x_stop):
            img[x_i, y_i, 0] = color_r
            img[x_i, y_i, 1] = color_g
            img[x_i, y_i, 2] = color_b
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_rect(x, y, w, h, img, color_r, color_g, color_b):
    """Draws a rectangle to img

    Args:
        x, int, x location in img
        y, int, y location in img
        w, int, width
        h, int, height
        img, np.array, 3D color image matrix
        color_r, int, red channel of color
        color_g, int, green channel of color
        color_b, int, blue channel of color
    """

    y_start = int(max(0, y))
    y_stop = int(min(y + h, img.shape[0] - 1))

    x_start = int(max(0, x))
    x_stop = int(min(x + w, img.shape[1] - 1))

    for y_i in range(y_start, y_stop):
        for x_i in range(x_start, x_stop):
            img[y_i, x_i, 0] = color_r
            img[y_i, x_i, 1] = color_g
            img[y_i, x_i, 2] = color_b
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def mandelbrot_color(matrix, output_file_name):
    """Generates a color version of the Mandelbrot Set

    Writes its output file to output_file_name

     Args:
        matrix: np.array, 2D array representing the mandelbrot set
        output_file_name: string, filename to write image to
    """

    # I wasn't quite sure on how to do the coloring, so I just interpolated
    # between two colors:
    color1 = np.array([[.2], [.2], [.8]])
    color2 = np.array([[1], [.2], [.5]])

    color_img = np.zeros((matrix.shape[0], matrix.shape[1], 3))

    color_img[:, :, 0] = color1[0] + matrix[:, :] * (color2[0] - color1[0])
    color_img[:, :, 1] = color1[1] + matrix[:, :] * (color2[1] - color1[1])
    color_img[:, :, 2] = color1[2] + matrix[:, :] * (color2[2] - color1[2])

    print("\nWriting image to:", output_file_name)
    skimage.io.imsave(output_file_name, color_img)
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_arrow(x0, y0, x1, y1, input_img, color):

    input_img = draw_line(x0, y0, x1, y1, input_img, color)

    dx = x1 - x0
    dy = y1 - y0

    #endpoint for one edge of arrow
    x2 = x0 + 0.75 * dx + 0.25 * (3 ** -0.5) * dy
    y2 = y0 + 0.75 * dy - 0.25 * (3 ** -0.5) * dx

    x3 = x0 + 0.75 * dx - 0.25 * (3 ** -0.5) * dy
    y3 = y0 + 0.75 * dy + 0.25 * (3 ** -0.5) * dx

    input_img = draw_line(x2, y2, x1, y1, input_img, color)
    input_img = draw_line(x3, y3, x1, y1, input_img, color)

    return input_img

#transform(TypeSpecialize(checks=False))
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def write_img(out_img, out_filename, do_clip=True):
    """Writes out_img to out_filename
    """
    if use_4channel and len(out_img.shape) == 3 and out_img.shape[2] == 4:
        out_img = out_img[:,:,:3]

    assert out_img is not None, 'expected out_img to not be None'
    out_img = numpy.clip(out_img, 0, 1) if do_clip else out_img
    if is_pypy:
        out_img = numpy.asarray(out_img*255, 'uint8')
        if len(out_img.shape) == 2:
            mode = 'L'
        elif len(out_img.shape) == 3:
            if out_img.shape[2] == 3:
                mode = 'RGB'
            elif out_img.shape[2] == 4:
                mode = 'RGBA'
            else:
                raise ValueError('unknown color image mode')
        else:
            raise ValueError('unknown number of dimensions for image')

        I = Image.frombytes(mode, (out_img.shape[1], out_img.shape[0]), out_img.tobytes())
        I.save(out_filename)
    else:
        try:
            skimage.io.imsave(out_filename, out_img)
        except:
            print('Caught exception while saving to {}: image shape is {}, min: {}, max: {}'.format(out_filename, out_img.shape, out_img.min(), out_img.max()))
            raise
项目:file-metadata    作者:pywikibot-catfiles    | 项目源码 | 文件源码
def alpha_blend(img, background=255):
        """
        Take an image, assume the last channel is a alpha channel and remove it
        by using the appropriate background.

        :param img:        The image to alpha blend into given background.
        :param background: The background color to use when alpha blending.
                           A scalar is expected, which is used for all
                           the channels.
        """
        alpha = img[..., -1] / 255.0
        channels = img[..., :-1]
        new_img = numpy.zeros_like(channels)
        for ichan in range(channels.shape[-1]):
            new_img[..., ichan] = numpy.clip(
                (1 - alpha) * background + alpha * channels[..., ichan],
                a_min=0, a_max=255)
        return new_img
项目:tf-sr-zoo    作者:MLJejuCamp2017    | 项目源码 | 文件源码
def rgb2gray(img):
    print img.shape
    img = skimage.color.rgb2gray(img)
    return img
项目:tf-sr-zoo    作者:MLJejuCamp2017    | 项目源码 | 文件源码
def rgb2gray(img):
    print img.shape
    img = skimage.color.rgb2gray(img)
    return img
项目:vsi_common    作者:VisionSystemsInc    | 项目源码 | 文件源码
def grouped_bar(features, bar_labels=None, group_labels=None, ax=None, colors=None):
  '''
  features.shape like np.array([n_bars, n_groups])

  >>> bars = np.random.rand(5,3)
  >>> grouped_bar(bars)

  >>> group_labels = ['group%d' % i for i in range(bars.shape[1])]
  >>> bar_labels = ['bar%d' % i for i in range(bars.shape[0])]
  >>> grouped_bar(bars, group_labels=group_labels, bar_labels=bar_labels)
  '''

  n_bars, n_groups = features.shape[0:2]

  if ax is None: 
    fig, ax = plt.subplots()
    fig.set_size_inches(9,6)
  else:
    fig = ax.get_figure()

  if colors is None: 
    colors = mpl.cm.spectral(np.linspace(0, 1, n_bars))

  index = np.arange(n_groups)
  bar_width = 1.0/(n_bars) * 0.75

  for j,group in enumerate(features):
    label = bar_labels[j] if bar_labels is not None else None
    ax.bar(index + j*bar_width - bar_width*n_bars/2.0, 
      group, bar_width, color=colors[j], label=label, alpha=0.4)
    ax.margins(0.05,0.0) # so the bar graph is nicely padded

  if bar_labels is not None:
    ax.legend(loc='upper left', bbox_to_anchor=(1.0,1.02), fontsize=14)

  if group_labels is not None:
    ax.set_xticks(index + (n_bars/2.)*bar_width - bar_width*n_bars/2.0)
    ax.set_xticklabels(group_labels, rotation=0.0)
    for item in (ax.get_xticklabels() + ax.get_yticklabels()):
      item.set_fontsize(14)
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_pacman_right(x, y, r, img, ma, color_r, color_g, color_b):
    """Draws a Pacman to img

    Args:
        x, int, x location in img (center of pacman)
        y, int, y location in img (center of pacman)
        r, int, radius of pacman
        img, np.array, 3D color image matrix
        ma, float, angle mouth is open at ("mouth angle")
        color_r, float, red channel of color
        color_g, float, green channel of color
        color_b, float, blue channel of color
    """

    y_start = int(max(0, y - r))
    y_stop = int(min(y + r, img.shape[0] - 1))

    for y_i in range(y_start, y_stop):
        x_start = int(x - math.sqrt(r**2 - (y - y_i)**2))
        x_stop = int(x + math.sqrt(r**2 - (y - y_i)**2))

        # top half of mouth:
        if y_i > y - float(r) * math.sin(ma) and y_i <= y:
            r_mouth = float(y - y_i) / math.sin(ma)
            x_stop = int(x + r_mouth * math.cos(ma))

        # bottom half of mouth:
        elif y_i < y + float(r) * math.sin(ma) and y_i > y:
            r_mouth = float(y_i - y) / math.sin(ma)
            x_stop = int(x + r_mouth * math.cos(ma))

        for x_i in range(x_start, x_stop):
            img[x_i, y_i, 0] = color_r
            img[x_i, y_i, 1] = color_g
            img[x_i, y_i, 2] = color_b

    # draw the eye:
    draw_circle(x, y - int(r / 2), int(r / 10.), img, 0, 0, 0)
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_pacman_right(x, y, r, img, ma, color_r, color_g, color_b):
    """Draws a Pacman to img

    Args:
        x, int, x location in img (center of pacman)
        y, int, y location in img (center of pacman)
        r, int, radius of pacman
        img, np.array, 3D color image matrix
        ma, float, angle mouth is open at ("mouth angle")
        color_r, float, red channel of color
        color_g, float, green channel of color
        color_b, float, blue channel of color
    """

    color = (color_r, color_g, color_b)

    y_start = int(max(0, y - r))
    y_stop = int(min(y + r, img.shape[0] - 1))

    for y_i in range(y_start, y_stop):
        x_start = int(x - math.sqrt(r**2 - (y - y_i)**2))
        x_stop = int(x + math.sqrt(r**2 - (y - y_i)**2))

        # top half of mouth:
        if y_i > y - float(r) * math.sin(ma) and y_i <= y:
            r_mouth = float(y - y_i) / math.sin(ma)
            x_stop = int(x + r_mouth * math.cos(ma))

        # bottom half of mouth:
        elif y_i < y + float(r) * math.sin(ma) and y_i > y:
            r_mouth = float(y_i - y) / math.sin(ma)
            x_stop = int(x + r_mouth * math.cos(ma))

        for x_i in range(x_start, x_stop):
            img[x_i, y_i] = color

    # draw the eye:
    draw_circle(x, y - int(r / 2), int(r / 10.), img, 0, 0, 0)

#transform(TypeSpecialize(checks=False))
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_rect(x, y, w, h, img, color_r, color_g, color_b):
    """Draws a rectangle to img

    Args:
        x, int, x location in img
        y, int, y location in img
        w, int, width
        h, int, height
        img, np.array, 3D color image matrix
        color_r, int, red channel of color
        color_g, int, green channel of color
        color_b, int, blue channel of color
    """

    color = (color_r, color_g, color_b)

    y_start = int(max(0, y))
    y_stop = int(min(y + h, img.shape[0] - 1))

    x_start = int(max(0, x))
    x_stop = int(min(x + w, img.shape[1] - 1))

    for y_i in range(y_start, y_stop):
        for x_i in range(x_start, x_stop):
            img[y_i, x_i, 0] = color_r
            img[y_i, x_i, 1] = color_g
            img[y_i, x_i, 2] = color_b

#transform(TypeSpecialize(checks=False))
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_arrow(x0, y0, x1, y1, input_img, color):

    #x0 = start_point[0]
    #y0 = start_point[1]

    #x1 = x0 + velocity[0]
    #y1 = y0 + velocity[1]

    input_img = draw_line(x0, y0, x1, y1, input_img, color)

    dx = x1 - x0
    dy = y1 - y0

    #endpoint for one edge of arrow
    x2 = x0 + 0.75 * dx + 0.25 * (3 ** -0.5) * dy
    y2 = y0 + 0.75 * dy - 0.25 * (3 ** -0.5) * dx

    x3 = x0 + 0.75 * dx - 0.25 * (3 ** -0.5) * dy
    y3 = y0 + 0.75 * dy + 0.25 * (3 ** -0.5) * dx

    input_img = draw_line(x2, y2, x1, y1, input_img, color)
    input_img = draw_line(x3, y3, x1, y1, input_img, color)

    return input_img

#transform(TypeSpecialize(checks=False))
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def find_color_value(dist, r):

    #dist is a 2D vector with magnitude smaller than 1, r is its manitude 
    #representing a position inside the color wheel

    angle = np.arctan2(dist[0], dist[1])
    color = np.array([0.0, 0.0, 0.0])

    if angle >= 0 and angle <= 2.0 * np.pi / 3.0:

        scale = angle * 3.0 / (2.0 * np.pi)
        color[0] = 1.0 - scale
        color[1] = scale

    if angle > 2.0 * np.pi / 3.0:

        scale = (angle - 2.0 * np.pi / 3.0) * 3.0 / (2.0 * np.pi)
        color[1] = 1.0 - scale
        color[2] = scale

    if angle < -2.0 * np.pi / 3.0:

        real_angle = angle + 2.0 * np.pi
        scale = (real_angle - 2.0 * np.pi / 3.0) * 3.0 / (2.0 * np.pi)
        color[1] = 1.0 - scale
        color[2] = scale

    if angle < 0 and angle >= -2.0 * np.pi / 3.0:

        real_angle = angle + 2.0 * np.pi
        scale = (real_angle - 4.0 * np.pi / 3.0) * 3.0 / (2.0 * np.pi)
        color[2] = 1.0 - scale
        color[0] = scale

    color *= r ** 0.25

    return color    

#transform(TypeSpecialize(checks=False))
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def read_img(in_filename, grayscale=False, extra_info={}):
    """Returns the image saved at in_filename as a numpy array.

    If grayscale is True, converts from 3D RGB image to 2D grayscale image.
    """
    if is_pypy:
        ans = Image.open(in_filename)
        height = ans.height
        width = ans.width
        channels = len(ans.getbands())
        if ans.mode == 'I':
            numpy_mode = 'uint32'
            maxval = 65535.0
        elif ans.mode in ['L', 'RGB', 'RGBA']:
            numpy_mode = 'uint8'
            maxval = 255.0
        else:
            raise ValueError('unknown mode')
        ans = numpy.fromstring(ans.tobytes(), numpy_mode).reshape((height, width, channels))
        ans = ans/maxval
        if grayscale and (len(ans.shape) == 3 and ans.shape[2] == 3):
            ans = ans[:,:,0]*0.2125 + ans[:,:,1]*0.7154 + ans[:,:,2]*0.0721
        if len(ans.shape) == 3 and ans.shape[2] == 1:
            ans = ans[:,:,0]
        return ans
    else:
        ans = skimage.io.imread(in_filename)
        if ans.dtype == numpy.int32:    # Work around scikit-image bug #1680
            ans = numpy.asarray(ans, numpy.uint16)
        ans = skimage.img_as_float(ans)
        if grayscale:
            ans = skimage.color.rgb2gray(ans)
#        print('here', use_4channel, len(ans.shape) == 3, ans.shape[2] == 3)
        if use_4channel and len(ans.shape) == 3 and ans.shape[2] == 3:
            ans = numpy.dstack((ans,) + (numpy.ones((ans.shape[0], ans.shape[1], 1)),))
            extra_info['originally_3channel'] = True
    return ans
项目:vsi_common    作者:VisionSystemsInc    | 项目源码 | 文件源码
def lblshow(label_img, labels_str=None, f=None, ax=None, cmap=None, *args, **kwargs):
  ''' display a labeled image with associated legend

  Parameters
  ----------
  label_img : labeled image [nrows, ncols] = numpy.array.shape
  labels_str : a complete list of labels
  f : (optional) a figure handle
  cmap : the color of each label (optional). like a list of colors, e.g.,
      ['Red','Green',...] or a matplotlib.colors.ListedColormap)
  '''

  if labels_str is None:
    labels_str = [str(i) for i in np.unique(label_img)]

  if ax is None:
    if f is None:
      f,ax = plt.subplots(1,1)
      f.set_size_inches(9,6)
    else:
      ax = f.gca()
  elif f is None:
    f = ax.get_figure() 


  nlabels = len(labels_str)
  if type(cmap) is mpl.colors.ListedColormap:
    pass
  elif hasattr(cmap, '__iter__'):
    if not kwargs.has_key('norm'):
      bounds = range(0,len(cmap)+1)
      kwargs['norm'] = mpl.colors.BoundaryNorm(bounds, len(cmap)) # HACKY
    cmap = mpl.colors.ListedColormap(cmap)
  elif cmap is None:
    colors = mpl.cm.spectral(np.linspace(0, 1, nlabels))
    cmap = mpl.colors.ListedColormap(colors)
  else:
    assert False, 'invalid color map'


  im = ax.imshow(label_img, cmap=cmap, *args, **kwargs); ax.axis('off')

  # create an axes on the right side of ax. The width of cax will be 5%
  # of ax and the padding between cax and ax will be fixed at 0.05 inch.
  divider = make_axes_locatable(ax)
  cax = divider.append_axes("right", size="5%", pad=0.05)
  cbar = plt.colorbar(im, cax=cax)

  cbar.ax.get_yaxis().set_ticks([])
  for j, lab in enumerate(labels_str):
    cbar.ax.text(1.3, float(2 * j + 1) / (nlabels*2), lab, ha='left', va='center')

  return f
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def draw_ghost(x, y, r, img, color_r, color_g, color_b, tf, blink):
    """Draws a ghost to img

    Args:
        x, int, x location in img
        y, int, y location in img
        r, int, radius of the ghosts's head
        img, np.array, 3D color image matrix
        color_r, int, red channel of color
        color_g, int, green channel of color
        color_b, int, blue channel of color
        tf, float, how much of ghost is not tentacles
        blink, boolean, whether or not the ghost should be blinking
    """

    y_start = int(max(0, y - r))
    y_stop = int(min(y + r, img.shape[1] - 1))

    for y_i in range(y_start, y_stop):
        x_start = int(x - math.sqrt(r**2 - (y - y_i)**2))
        x_stop = int(x + math.sqrt(r**2 - (y - y_i)**2))

        # bottom half of ghost:
        if y_i > y:
            x_start = int(max(0, x - r))
            x_stop = int(min(x + r, img.shape[0] - 1))

        # print(x_start, x_stop, y_start, y_stop)

        for x_i in range(x_start, x_stop):
            if y_i <= y + tf * r:
                img[x_i, y_i, 0] = color_r
                img[x_i, y_i, 1] = color_g
                img[x_i, y_i, 2] = color_b
            else:
                if x_i < x - r * 5/7. or (x_i > x - r * 3/7. and x_i < x - r * 1/7.) or (x_i > x + r * 1/7. and x_i < x + r * 3/7.) or (x_i > x + r * 5/7.):
                    img[x_i, y_i, 0] = color_r
                    img[x_i, y_i, 1] = color_g
                    img[x_i, y_i, 2] = color_b

    # draw the eye:
    if not blink:
        draw_circle(x - int(r / 4), y - int(r / 2), int(r / 5.), img, 1, 1, 1)
        draw_circle(x + int(r / 4), y - int(r / 2), int(r / 5.), img, 1, 1, 1)
        draw_circle(x - int(r / 8.), y - int(r / 2), int(r / 9.), img, 0, 0, 1)
        draw_circle(x + int(r * 3 / 8.), y - int(r / 2), int(r / 9.), img, 0, 0, 1)
    else:
        draw_rect(y - int(r / 2), x - int(r / 4), r / 8., r / 4., img, 0, 0, 0)
        draw_rect(y - int(r / 2), x + int(r / 4), r / 8., r / 4., img, 0, 0, 0)
项目:vizgen    作者:uva-graphics    | 项目源码 | 文件源码
def optical_flow_ssd(input_img1, input_img2):

    h = input_img1.shape[0]
    w = input_img1.shape[1]

    output_img = np.zeros(input_img1.shape, 'float32')
    output_img[:, :, :] = input_img2[:, :, :]
    u = np.zeros([h, w], 'float32')
    v = np.zeros([h, w], 'float32')

    window_size = 21
    offset = int((window_size - 1) / 2.0)

    summed_ssd = np.zeros([input_img1.shape[0], input_img1.shape[1], window_size ** 2], 'float32')

    for r in range(window_size):
        for c in range(window_size):
            offset_y = r - offset
            offset_x = c - offset
            ind = window_size * r + c
            summed_ssd[:, :, ind] = calc_summed_ssd(input_img1, input_img2, offset_y, offset_x)

    max_of = 0.0

    for r in range(offset, h - offset):
        for c in range(offset, w - offset):

            ssd = summed_ssd[r + offset, c + offset, :] + summed_ssd[r - offset - 1, c - offset - 1, :] - summed_ssd[r + offset, c - offset - 1, :] - summed_ssd[r - offset - 1, c + offset, :]

            ind = np.argmin(ssd)

            offset_c = ind % window_size
            offset_r = (ind - offset_c) // window_size

            offset_y = offset_r - offset
            offset_x = offset_c - offset

            u[r, c] = offset_x
            v[r, c] = offset_y

            if (u[r, c] ** 2 + v[r, c] ** 2) ** 0.5 > max_of:
                max_of = (u[r, c] ** 2 + v[r, c] ** 2) ** 0.5

    for r in range(offset, h - offset, 10):
        for c in range(offset, w - offset, 10):

            scale = ((u[r, c] ** 2 + v[r, c] ** 2) ** 0.5) / max_of
            dist = np.array([u[r, c], v[r, c]], 'float32') / max_of
            color = find_color_value(dist, scale)
            output_img = draw_arrow(float(r), float(c), float(r - u[r, c]), float(c - v[r, c]), output_img, color = color)

    output_img = output_img[20 : h - 20, 20 : w - 20, :]

    return output_img

#transform(TypeSpecialize(checks=False))
项目:file-metadata    作者:pywikibot-catfiles    | 项目源码 | 文件源码
def fetch(self, key=''):
        if key == 'filename_raster':
            # A raster filename holds the file in a raster graphic format
            return self.fetch('filename')
        elif key == 'filename_zxing':
            return pathlib2.Path(self.fetch('filename_raster')).as_uri()
        elif key == 'ndarray':
            Image.MAX_IMAGE_PIXELS = self.config('max_decompressed_size')
            try:
                image_array = skimage.io.imread(self.fetch('filename_raster'))
                if image_array.shape == (2,):
                    # Assume this is related to
                    # https://github.com/scikit-image/scikit-image/issues/2154
                    return image_array[0]
                return image_array
            except Image.DecompressionBombWarning:
                logging.warn('The file "{0}" contains a lot of pixels and '
                             'can take a lot of memory when decompressed. '
                             'To allow larger images, modify the '
                             '"max_decompressed_size" config.'
                             .format(self.fetch('filename')))
                # Use empty array as the file cannot be read.
                return numpy.ndarray(0)
        elif key == 'ndarray_grey':
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                return skimage.img_as_ubyte(
                    skimage.color.rgb2grey(self.fetch('ndarray')))
        elif key == 'ndarray_hsv':
            with warnings.catch_warnings():
                warnings.simplefilter("ignore")
                return skimage.img_as_ubyte(
                    skimage.color.rgb2hsv(self.fetch('ndarray_noalpha')))
        elif key == 'ndarray_noalpha':
            if self.is_type('alpha'):
                return self.alpha_blend(self.fetch('ndarray'))
            return self.fetch('ndarray')
        elif key == 'pillow':
            pillow_img = Image.open(self.fetch('filename_raster'))
            self.closables.append(pillow_img)
            return pillow_img
        return super(ImageFile, self).fetch(key)
项目:file-metadata    作者:pywikibot-catfiles    | 项目源码 | 文件源码
def analyze_color_calibration_target(self):
        """
        Find whether there is a color calibration strip on top of the image.
        """
        grey_array = self.fetch('ndarray_grey')
        image_array = self.fetch('ndarray')
        if grey_array is None:
            return {}

        # For the images we're testing, the IT8 bar takes about 20% of the
        # image and also in the 20% we need the mid area
        bary = int(0.2 * grey_array.shape[0])

        def bar_intensity(x):
            sampley = max(int(0.1 * x.shape[0]), 2)
            return numpy.mean(
                x[(x.shape[0] - sampley) // 2:(x.shape[0] + sampley) // 2,
                  :, ...],
                axis=0)

        topbar = bar_intensity(grey_array[:bary, :, ...])
        botbar = bar_intensity(grey_array[-bary:, :, ...])

        def _merge_near(arr):
            out = []
            last_elem = arr[0]
            out.append(last_elem)
            for elem in arr[1:]:
                if elem != last_elem:
                    out.append(elem)
                last_elem = elem
            return numpy.asarray(out)

        # Bottom bars seem to have smaller intensity because of the background
        # Hence, we set a smaller threshold for peaks in bottom bars.
        bot_spikes = _merge_near((numpy.diff(botbar)) > -2.5).sum()
        top_spikes = _merge_near((numpy.diff(topbar)) < 3).sum()
        top_grey_mse, bot_grey_mse = 0, 0
        if image_array.ndim == 3:
            for chan in range(image_array.shape[2]):
                top_grey_mse += (
                    (image_array[bary:, :, chan] -
                     grey_array[bary:]) ** 2).mean()
                bot_grey_mse += (
                    (image_array[-bary, :, chan] -
                     grey_array[-bary]) ** 2).mean()
            top_grey_mse /= 3.0
            bot_grey_mse /= 3.0

        data = {}
        if 15 < top_spikes < 25:
            data['Color:IT8TopBar'] = top_spikes
            data['Color:IT8TopBarGreyMSE'] = top_grey_mse
        if 15 < bot_spikes < 25:
            data['Color:IT8BottomBar'] = bot_spikes
            data['Color:IT8BottomBarGreyMSE'] = bot_grey_mse

        return data