ImageMagick与二进制图像上的OpenCV

时间:2017-03-25 19:14:10

标签: opencv imagemagick

基于this question,我正在使用OpenCV和Imagemagick工具进行一些测试。

ImageMagick代码

考虑以下IM代码及其输出:(rect.png

convert -size 100x60 xc:white -fill black -draw "rectangle 20,10 80,50" rect.png
convert rect.png -format %c histogram:info:-
2501: (  0,  0,  0) #000000 gray(0)
3499: (255,255,255) #FFFFFF gray(255)

请注意2501 + 3499 = 6000 = 100 * 60,与图片大小兼容。因此IM确认图像仅包含黑白像素。

OpenCV代码

考虑下面的代码,它应该打印非B / W像素:

#include <iostream>
#include <opencv2/opencv.hpp>

using namespace std;
using namespace cv;

int main(int, char** argv)
{
       Mat img = imread(argv[1]); // CV_LOAD_IMAGE_GRAYSCALE
       Mat image = img;

        for (int y=0; y<img.rows;y++)
        {
            for (int x=0; x<img.cols;x++)
            {
                if (static_cast<int>(img.at<uchar>(x,y)) != 0 && static_cast<int>(img.at<uchar>(x,y)) != 255)
                {
                cout << "(" << x <<","<< y <<")="<< static_cast<int>(img.at<uchar>(x,y)) << endl;
                }
            }
        }
}

上面创建的rect.png上的输出是:

(64,3)=240
(63,5)=240
(65,5)=127
(65,7)=240
(64,11)=127
(65,11)=240
(64,13)=240
(64,17)=240
(63,19)=240
(65,19)=127
(65,21)=240
(60,24)=97
(64,25)=127
(65,25)=240
(64,27)=240
(64,31)=240
(60,32)=112
(60,33)=89
(63,33)=240
(65,33)=127
(60,34)=4
(60,35)=1
(65,35)=240
(64,39)=127
(65,39)=240
(60,40)=112
(60,41)=89
(64,41)=240
(60,42)=4
(60,43)=1
(64,45)=240
(63,47)=240
(65,47)=127
(65,49)=240
(60,52)=2
(64,53)=127
(65,53)=240
(64,55)=240
(60,56)=160
(60,57)=89
(60,58)=4
(60,59)=1
(64,59)=240

问题:发生了什么事?图像是二进制还是不是?

1 个答案:

答案 0 :(得分:3)

除了在RGB与BGR方面呈现前瞻性之外,OpenCV在索引方面也是前瞻性的: - )

你的专栏:

if (static_cast<int>(img.at<uchar>(x,y)) != 0 && static_cast<int>(img.at<uchar>(x,y)) != 255)

应该是

if (static_cast<int>(img.at<uchar>(y,x)) != 0 && static_cast<int>(img.at<uchar>(y,x)) != 255)

我所说的是行索引在列索引之前。