在Python中将二进制图像转换为2D数组或Matrix?

时间:2016-12-01 11:09:09

标签: python python-2.7 numpy image-processing

我对图像处理很陌生,而且我很难理解其中的内容......所以我们的想法是如何在python中使用二进制图像创建矩阵?

这样的事情:

尽管存在重点,但它不是同一个图像。 谢谢你的帮助,我很感激欢呼

2 个答案:

答案 0 :(得分:2)

使用cv2 - 阅读更多here

import cv2
img = cv2.imread('path/to/img.jpg')
resized = cv2.resize(img, (128, 128), cv2.INTER_LINEAR)
print pic

使用skimage - 阅读更多here

import skimage.io as skio
faces = skio.imread_collection('path/to/images/*.pgm',conserve_memory=True) # can load multiple images at once

使用Scipy - 阅读更多here

from scipy import misc
pic = misc.imread('path/to/img.jpg')
print pic

绘制图像

import matplotlib.pyplot as plt
plt.imshow(faces[0],cmap=plt.cm.gray_r,interpolation="nearest")
plt.show()

答案 1 :(得分:0)

我目前正在使用的示例。

"""
A set of utilities that are helpful for working with images. These are utilities
needed to actually apply the seam carving algorithm to images
"""


from PIL import Image


class Color:
    """
    A simple class representing an RGB value.
    """

    def __init__(self, r, g, b):
        self.r = r
        self.g = g
        self.b = b

    def __repr__(self):
        return f'Color({self.r}, {self.g}, {self.b})'

    def __str__(self):
        return repr(self)


def read_image_into_array(filename):
    """
    Read the given image into a 2D array of pixels. The result is an array,
    where each element represents a row. Each row is an array, where each
    element is a color.

    See: Color
    """

    img = Image.open(filename, 'r')
    w, h = img.size

    pixels = list(Color(*pixel) for pixel in img.getdata())
    return [pixels[n:(n + w)] for n in range(0, w * h, w)]


def write_array_into_image(pixels, filename):
    """
    Write the given 2D array of pixels into an image with the given filename.
    The input pixels are represented as an array, where each element is a row.
    Each row is an array, where each element is a color.

    See: Color
    """

    h = len(pixels)
    w = len(pixels[0])

    img = Image.new('RGB', (w, h))

    output_pixels = img.load()
    for y, row in enumerate(pixels):
        for x, color in enumerate(row):
            output_pixels[x, y] = (color.r, color.g, color.b)

    img.save(filename)