大きなデータを得たとして、その特徴を画像の濃淡で可視化したり、画像処理の技法で分析したりするかもしれない、と考え、その準備として、 numpy の配列と OpenCV の出力について、いくつか試してみた。
枠
OpenCV と numpy を import しておく。後述のコードは、全てこの2つのライブラリを import して動かしている。
import cv2
import numpy as np
画像データは、3次元配列で表現される。各次元は、行、列、色 に対応する。
img = np.zeros((300, 300, 3), np.uint8)
cv2.imwrite("01.jpg",img)

色の設定
色は、B, G, R の順番で記述される。
img = np.zeros((300, 300, 3), np.uint8)
img[:,:] = [255, 0, 0] # B G R の順
cv2.imwrite("02.jpg",img)

行のスライス
img = np.zeros((300, 300, 3), np.uint8)
img[ 0:100,:] = [255, 0, 0]
img[100:200,:] = [ 0, 255, 0]
img[200:300,:] = [ 0, 0, 255]
cv2.imwrite("03.jpg",img)

列のスライス
img = np.zeros((300, 300, 3), np.uint8)
img[:, 0:100] = [255, 0, 0]
img[:, 100:200] = [255, 255, 255]
img[:, 200:300] = [ 0, 0, 255]
cv2.imwrite("04.jpg",img)

行列の座標を指定して、数値を入力
img = np.zeros((256, 256, 3), np.uint8)
print(img.shape)
for i in range(256):
for j in range(256):
img[i,j] = [i, j, 0]
cv2.imwrite("05.jpg",img)

float32 で計算して、最後に uint8 の画像にする
小数や大きな数を扱うために、 float32 を使い後で丸めて整数にする。
img = np.zeros((256, 256, 3), np.float32)
print(img.shape)
for i in range(256):
for j in range(256):
img[i,j] = [i ** 2, j ** 2, (i ** 2 + j ** 2)/2.]
cv2.imwrite("06.jpg",np.uint8(np.clip(img/256., 0, 255)))

ランダムウォーク
import random
img = np.zeros((256, 256, 3), np.uint8)
img.fill(255)
pos = [127, 127]
for i in range(3000):
pos = [pos[0] + random.randint(-1, 1),
pos[1] + random.randint(-1, 1)]
img[pos[0], pos[1]] = [255, 0, 0]
cv2.imwrite("07.jpg",img)

コメント