0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

ファイルをbytesで読み込んで、plt.show()可能なnumpy形式までの変換を丁寧にみていく

Last updated at Posted at 2023-06-02

記事の目的

f.readで読み込んでからのファイル形式の理解が深まる

準備するもの

画像データを適当にとってきて、filename = のところを書き換えたら使えます

import matplotlib.pyplot as plt
import numpy as np
import cv2 


# 型確認のための汎用メソッド
def showDetail(obj,name):
    obj_type = type(obj)
    print(f"type({name})",obj_type) 
    if obj_type == np.ndarray:
        print(f"{name}.shape",obj.shape) 
    
filename = 'images/testImage.jpg'

# Read image into memory
payload = None
with open(filename, 'rb') as f:
    payload = f.read()
showDetail(payload,"payload") # type(payload) <class 'bytes'>

frombuff = np.frombuffer(payload, dtype='uint8') # byteをnumpyにしている(1次元)
showDetail(frombuff,"frombuff") # frombuff.shape (3002800,)

input_data = cv2.imdecode(frombuff, cv2.IMREAD_UNCHANGED) # numpyを画像の形式にdecodeしている。
showDetail(input_data,"input_data") # input_data.shape (2565, 3500, 3)


plt.imshow(input_data) 
plt.show()

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?