vision.exif.orientation

ExifのOrientation属性


ExifのOrientation属性の扱いが意外と厄介なので、ImageMagickを使った処理とともにここにまとめておきます。

スマートフォンやデジタルカメラ等で撮影された画像には通常、画像データそのものに加え、日時や機材などのメタ情報もExifという形式で保存されています。
その中には画像の向きというか回転情報がOrientation属性として保存され、ImageMagickのコマンドidentifyを使うと次のように確認できます。
$ identify -verbose IMG_5223.JPG | grep Orientation
  Orientation: TopLeft
$ identify -verbose IMG_5224.JPG | grep Orientation
  Orientation: RightTop
$ identify -verbose IMG_5225.JPG | grep Orientation
  Orientation: BottomRight
$ identify -verbose IMG_5226.JPG | grep Orientation
  Orientation: LeftBottom
まず、TopLeftなどの表記が分かりにくいので、以下に写真とともにまとめておきます。
building_TopLeft.png TopLeft (上辺が被写体のTopで、左辺が被写体のLeft)
building_RightTop.png RightTop (上辺が被写体のRightで、左辺が被写体のTop)
building_BottomRight.png BottomRight (上辺が被写体のBottomで、左辺が被写体のRight)
building_LeftBottom.png LeftBottom (上辺が被写体のLeftで、左辺が被写体のBottom)

ブラウザを始めとしたさまざまなソフトウェア、またさまざまなサービスが、これらの情報をいかに扱うかに関して統一されておらず、またExif形式のバージョンによる違いもあり、表示した画像が意図せず回転してしまい、厄介なことになります。
この問題を回避するために、ImageMagickを使って、画像を回転し、Orientation属性を通常のTopLeftに修正してみます。
$ identify -verbose IMG_5226.JPG | grep Orientation
  Orientation: LeftBottom
$ mogrify -auto-orient IMG_5226.JPG 
$ identify -verbose IMG_5226.JPG | grep Orientation
  Orientation: TopLeft
これで回転された画像に置き換わり、Orientation属性はLeftBottomから通常のTopLeftに書き換えられます。

最近のスマートフォンで撮影された画像ならばこれで解決すると思いますが、困ったことに、デジタルカメラで撮影された古い写真などはOrientation属性はTopLeftになるものの、画像自体が回転されていないことがあります。
その場合はコマンドmogrifyまたはコマンドconvertで -rotate -90 等で角度を指定して手動で回転させる必要があります。
$ identify -verbose IMG_0926.JPG | grep Orientation
  Orientation: RightTop
$ mogrify -quality 100 -auto-orient IMG_0926.JPG 
$ identify -verbose IMG_0926.JPG | grep Orientation
  Orientation: TopLeft
$ mogrify -quality 100 -rotate -90 IMG_0926.JPG
$ identify -verbose IMG_0926.JPG | grep Orientation
  Orientation: TopLeft
-- Kohji 2020-09-26

例えば、時計回りに90度回転してしまっているRightTopの写真は、写真の向きは正しいのにRightTopという情報自体が正しくないと判断できます。
  • auto-orientでTopLeftに変更し、それでも写真の向きがおかしければ-rotate -90で反時計回りに回転させます。
$ mogrify -quality 100 -auto-orient IMG_0942.JPG 
$ mogrify -quality 100 -rotate -90 IMG_0942.JPG
-- Kohji 2022-02-06

回転情報を含め、Exifの情報を削除してしまうには、次のようにします。
$ mogrify -quality 100 -strip IMG_0941.JPG
-- Kohji 2020-12-30

TopLeftか否かの確認

大量のファイルをPythonスクリプトで処理してみます。
import re
import sys
import glob
import subprocess

jpegs = glob.glob('IMG_*.jpeg')
print(len(jpegs))

for jpeg in jpegs:
  result = subprocess.run(('identify', '-verbose', jpeg), stdout = subprocess.PIPE)
  re_search = re.search(r'\sOrientation: (\w+)\s', result.stdout.decode('utf-8'))
  if re_search:
    if re_search.group(1) == 'TopLeft': continue
    print(jpeg, re_search.group(1), sep = ': ')
  else:
    sys.stderr.write('Error: ' + jpeg + '\n')
-- Kohji 2022-10- 29





  • 最終更新:2022-10-29 16:33:30

このWIKIを編集するにはパスワード入力が必要です

認証パスワード