計算機視覺必知 - 用Python將任一圖片轉換為向量矩陣 image2vector

Anish Hui發表於2020-11-29

需求:將我本地任意張圖片轉換為向量形式

girl.jpg
在這裡插入圖片描述

import numpy as np
from PIL import Image

img = Image.open('girl.jpg').convert('RGBA')
arr = np.array(img)

# record the original shape
shape = arr.shape

# make a 1-dimensional view of arr
flat_arr = arr.ravel()

# convert it to a matrix
vector = np.matrix(flat_arr)

# do something to the vector
vector[:,::10] = 128

# reform a numpy array of the original shape
arr2 = np.asarray(vector).reshape(shape) # 把圖片轉換為向量形式


# make a PIL image
img2 = Image.fromarray(arr2, 'RGBA')

# img2 = Image.fromarray(arr2 * 3, 'RGBA')
# print(246 * 3 - 256 * 2) # 超過255會自動減去256

img2.show()
img2.save('out.png') # 儲存圖片

arr2

arr2為圖片的向量形式

array([[[128, 182, 175, 255],
        [167, 182, 175, 255],
        [167, 182, 128, 255],
        ...,
        [166, 183, 128, 255],
        [166, 183, 177, 255],
        [166, 183, 177, 255]],

       [[128, 182, 175, 255],
        [167, 182, 175, 255],
        [167, 182, 128, 255],
        ...,
        [166, 183, 128, 255],
        [166, 183, 177, 255],
        [166, 183, 177, 255]],

       [[128, 181, 174, 255],
        [166, 181, 176, 255],
        [166, 181, 128, 255],
        ...,
        [166, 183, 128, 255],
        [166, 183, 177, 255],
        [166, 183, 177, 255]],

       ...,

       [[128,  73,  80, 255],
        [ 96,  75,  82, 255],
        [ 98,  77, 128, 255],
        ...,
        [ 67,  77, 128, 255],
        [ 64,  77,  86, 255],
        [ 64,  77,  86, 255]],

       [[128,  59,  66, 255],
        [ 83,  62,  69, 255],
        [ 85,  64, 128, 255],
        ...,
        [ 66,  76, 128, 255],
        [ 64,  77,  86, 255],
        [ 64,  77,  86, 255]],

       [[128,  53,  60, 255],
        [ 76,  55,  62, 255],
        [ 78,  57, 128, 255],
        ...,
        [ 65,  75, 128, 255],
        [ 64,  77,  86, 255],
        [ 64,  77,  86, 255]]], dtype=uint8)

out.jpg
在這裡插入圖片描述

相關文章