0
4

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 3 years have passed since last update.

python で Photoshop形式のファイル(.psd)を読み込む

Last updated at Posted at 2021-06-26

#はじめに
pytoshop の利用に関する記事が少なかったので,PSD形式のファイルに対して各レイヤーの画像を Numpy形式で取り出す方法を共有しておきます.

#やりたいこと
pytoshop というライブラリを使って PSDファイルを読み込み,各レイヤーの画像データを Numpy配列の形式で読み込みます.
そして,全てのレイヤー画像を jpg形式で出力します.
今回は行っていませんが,得られた Numpy配列に操作を加えることで OpenCV による処理を加えることができます.
また,文字化け対策として imwrite関数を定義しておくと良いようです.
同様に imread関数についても,このリンク先に記述があります.
https://qiita.com/SKYS/items/cbde3775e2143cad7455

#スクリプト

#! env python
# -*- coding: utf-8 -*-

import numpy as np
import cv2
import pytoshop

def imwrite(filename, img, params=None):
    try:
        ext = os.path.splitext(filename)[1]
        result, n = cv2.imencode(ext, img, params)

        if result:
            with open(filename, mode='w+b') as f:
                n.tofile(f)
            return True
        else:
            return False
    except Exception as e:
        print(e)
        return False

def main():
    read_file_path = 'test.psd'

    with open(read_file_path, 'rb') as rfd:
        psd = pytoshop.read(rfd)
        
        for i in range(len(psd._layer_and_mask_info._layer_info._layer_records)):
            write_file_name = psd._layer_and_mask_info._layer_info._layer_records[i]._name + ".jpg"
            # アルファ値は psd._layer_and_mask_info._layer_info._layer_records[i]._channels[-1].image
            layer_R = psd._layer_and_mask_info._layer_info._layer_records[i]._channels[2].image
            layer_G = psd._layer_and_mask_info._layer_info._layer_records[i]._channels[1].image
            layer_B = psd._layer_and_mask_info._layer_info._layer_records[i]._channels[0].image
            # image に画像データが含まれており,OpenCV などで加工可能
            image = np.stack([layer_R,layer_G,layer_B], axis=2)
            imwrite(write_file_name, image)

if __name__ == '__main__':
    main()

#参考
pytoshop を利用する上で参考にしたサイトもまとめておきます.
https://qiita.com/mm_sys/items/ba139c9f4dcc0ac38156
https://pytoshop.readthedocs.io/en/latest/api.html

0
4
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
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?