画像ファイルからRGB値を取り出す

convert コマンドで各画素のRGB値を取得し、MYSQLを使用して色調加工するというスクリプトです。convert コマンドの使用方法については、

ImageMagickで画像からRGB値を取り出す、またその逆 - Qiita

大変参考にさせて頂きましたので、ほとんど備忘録のようなものです。

 

f:id:S_E_Hyphen:20180324153553j:plain
f:id:S_E_Hyphen:20180324153614j:plain
左:元画像     右:加工後

 

#!/bin/bash
#convert -resize 240x432 photo_org/DSC00097.JPG 崖.jpg
#convert -resize x432 -crop 240x432+50+0 photo_org/DSC00098.JPG 海.jpg
#convert -auto-orient -resize x432 photo_org/P3060023.JPG 椿.jpg
#convert -auto-orient -resize x432 photo_org/P6120012.JPG 百合.jpg
# ImageMagick pixel enumeration: 243,432,255,srgb

for thema in 海 # 画像ファイル
do

temp=`mktemp ./XXXX.tmp`

# JPEG形式を平テキストに変換し、データベース登録
convert ${thema}.jpg txt: |\
 awk -F"[,:)]" 'NR>1{print $1,$2,$3,$4,$5}' |\
 sed -e "s/(//g" |\
 awk '{print $1,$2,$3,$4,$5}' > $temp
mysql image << _SQL_
 drop table if exists ${thema};
 create table ${thema} (
  x int,
  y int,
  r int,
  g int,
  b int
 );
 load data local infile "$temp" 
    into table ${thema}
    fields terminated by " "(x,y,r,g,b);
_SQL_

rm $temp

# XY方向それぞれの画素数を取得
nx=`mysql image -N <<_SQL_
 select max(x)-min(x)+1 from ${thema};
_SQL_`
ny=`mysql image -N <<_SQL_
 select max(y)-min(y)+1 from ${thema};
_SQL_`

# ここで赤画層と緑画層の加工を実施 mysql image << _SQL_ update ${thema} set r=0 where b-r>48; update ${thema} set g=0 where b-g>64; _SQL_ # CONVERTコマンドで使用可能なテキストファイルに変換 printf "# ImageMagick pixel enumeration: %d,%d,255,srgb\n" $nx $ny > ${thema}.txt mysql image -N <<_SQL_ > $temp select x,y,r,g,b from ${thema} order by x,y; _SQL_ cat $temp |\ awk '{printf "%3d,%3d: (%3d,%3d,%3d)\n",$1,$2,$3,$4,$5}' \ >> ${thema}.txt # テキスト形式を再度JPG形式画像に変換 convert ${thema}.txt ${thema}_blue.jpg rm $temp done