LoginSignup
4

More than 5 years have passed since last update.

MISC for 画像処理

Last updated at Posted at 2014-12-27

これは何?

画像処理をするときに細々としたデータを扱うときのちょっとしたコマンドなどです。
メモ代わりで随時更新します。

コマンドライン

convertコマンドでカラー画像をグレースケールに変換する

convert <入力ファイル名> -set colorspace Gray -separate -average <出力ファイル名>

多分 -set colorspace Gray さえすれば良さそう。
出典 : http://stackoverflow.com/questions/13317753/convert-rgb-to-grayscale-in-imagemagick-command-line

convertコマンドでjpg, png を ppmに変換する

convert <入力ファイル名> output_file_name.ppm

メモ:出力ファイル名の拡張子がppmだったらよさそう。

Macでppmファイルを見る → ppmファイルをjpgなどに変換する。

Finderで見ることが出来なさそう。Chromeとかでも見れない。ので上と逆にppmファイルをjpegファイルに変換してみる

convert image.ppm image.jpg && open image.jpg

iOSで画像処理

CMSampleBufferをOpenCVのmatに変換する


#import <opencv.hpp>
#import <ios.h>

cv::Mat3b sampleBufferToMat(CMSampleBufferRef sampleBuffer)
{
    CVImageBufferRef pixelBuffer = CMSampleBufferGetImageBuffer(sampleBuffer);

    CVPixelBufferLockBaseAddress( pixelBuffer, 0 );

    //Processing here
    int bufferWidth = (int)CVPixelBufferGetWidth(pixelBuffer);
    int bufferHeight = (int)CVPixelBufferGetHeight(pixelBuffer);
    unsigned char *pixel = (unsigned char *)CVPixelBufferGetBaseAddress(pixelBuffer);

    // put buffer in open cv, no memory copied
    cv::Mat4b mat = cv::Mat(bufferHeight,bufferWidth,CV_8UC4,pixel);
    cv::Mat3b mat3b(bufferHeight, bufferWidth);
    cvtColor(mat, mat3b, CV_BGRA2RGB);

    //End processing
    CVPixelBufferUnlockBaseAddress( pixelBuffer, 0 );

    return mat3b;

}

RGB3チャンネルのcv::Matが返ります。
メモリはCMSampleBufferのものを利用せず、新たに確保しています。

cv::Mat -> UIImage

特に何も考えなければ


UIImage *img = MatToUIImage(mat);

でOK

他にもいろいろと考える事がある場合は、こんな感じで。

UIImage* matToUIImage(const cv::Mat& mat, CGFloat scale, UIImageOrientation orientation)
{
    UIImage *img;
    if (mat.channels() == 3) {
        cv::Mat4b mat4b(mat.size());
        cvtColor(mat, mat4b, CV_RGB2RGBA);
        img = MatToUIImage(mat4b);
    } else {
        img = MatToUIImage(mat);
    }

    return [UIImage imageWithCGImage:img.CGImage
                               scale:scale
                         orientation:orientation];
}

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
4