done is better than perfect

自分が学んだことや、作成したプログラムの記事を書きます。すべての記載は他に定める場合を除き個人的なものです。

Install OpenCV via Homebrew

TL;DR

  • Use Homebrew
  • You can use Xcode!

1. Uninstall Macports

Unfortunately, Macports and Homebrew will not coexist well together. Before installing Homebrew, you should uninstall Macports.

(If you can’t uninstall it for some reason, please let me know)

See this to uninstall.

2. Install Homebrew

You need to install Homebrew. It is a Macports-like package manager for OS X. To install, please type this in a Terminal;

ruby -e "$(curl -fsSL https://raw.github.com/Homebrew/homebrew/go/install)”

After installation, you should type this to verity the installation.

brew doctor

If the output is;

Your system is ready to brew.

You have done the installation.

3. Install OpenCV

Type this command;

brew tap homebrew/science

And then, you can install OpenCV by using Homebrew;

brew install opencv

4. Write a face detection code and run with Xcode

f:id:thekoruku:20140529110854p:plain

f:id:thekoruku:20140529110921p:plain

f:id:thekoruku:20140529110932p:plain

f:id:thekoruku:20140529112654p:plain

f:id:thekoruku:20140529111013p:plain

f:id:thekoruku:20140529111028p:plain

  • NOTE: You may need to make a link to /usr/local/include in a FAVORITES by using Finder.

f:id:thekoruku:20140529112715p:plain

  • Copy this code

Before running this code, you should download a face image and replace "PATH/TO/IMAGE" with the path to the image.

#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>
#include <opencv2/objdetect/objdetect.hpp>
#include <opencv2/highgui/highgui.hpp>

using namespace std;
using namespace cv; 

int main(int argc, char *argv[]) {
    const char *imagename = "PATH/TO/IMAGE";
    Mat img = imread(imagename, 1); 
    if (img.empty()) return -1; 

    double scale = 4.0;
    Mat gray, smallImg(saturate_cast<int>(img.rows/scale), saturate_cast<int>(img.cols/scale), CV_8UC1);
    cvtColor(img, gray, CV_BGR2GRAY);
    resize(gray, smallImg, smallImg.size(), 0, 0, INTER_LINEAR);
    equalizeHist(smallImg, smallImg);

    string cascadeName = "/usr/local/share/OpenCV/haarcascades/haarcascade_frontalface_alt.xml";
    CascadeClassifier cascade;
    if (!cascade.load(cascadeName)) return -1; 

    vector<Rect> faces;
    cascade.detectMultiScale(smallImg, faces,
            1.1, 2,
            CV_HAAR_SCALE_IMAGE,
            Size(30, 30));
    vector<Rect>::const_iterator r = faces.begin();
    for (; r!= faces.end(); r++) {
        Point center;
        int radius;
        center.x = saturate_cast<int>((r->x + r->width*0.5)*scale);
        center.y = saturate_cast<int>((r->y + r-> height*0.5)*scale);
        radius = saturate_cast<int>((r->width + r->height)*0.25*scale);
        circle(img, center, radius, Scalar(80, 80, 255), 3, 8, 0); 
    }   
    namedWindow("result", CV_WINDOW_AUTOSIZE | CV_WINDOW_FREERATIO);
    imshow("result", img);
    waitKey(0);
}

f:id:thekoruku:20140529111203p:plain