在差异区域周围绘制矩形

时间:2016-03-11 11:06:15

标签: c++ opencv visual-studio-2012

我有一个我无法解决的问题。我正在使用OpenCV来区分两个图像。我正在单独AbsDiff获得输出。使用的差异方法是char imgName[15]; Mat img1 = imread(image_path1, COLOR_BGR2GRAY); Mat img2 = imread(image_path2, COLOR_BGR2GRAY); /*cvtColor(img1, img1, CV_BGR2GRAY); cvtColor(img2, img2, CV_BGR2GRAY);*/ cv::Mat diffImage; cv::absdiff(img2, img1, diffImage); cv::Mat foregroundMask = cv::Mat::zeros(diffImage.rows, diffImage.cols, CV_8UC3); float threshold = 30.0f; float dist; for(int j=0; j<diffImage.rows; ++j) { for(int i=0; i<diffImage.cols; ++i) { cv::Vec3b pix = diffImage.at<cv::Vec3b>(j,i); dist = (pix[0]*pix[0] + pix[1]*pix[1] + pix[2]*pix[2]); dist = sqrt(dist); if(dist>threshold) { foregroundMask.at<unsigned char>(j,i) = 255; } } } sprintf(imgName,"D:/outputer/d.jpg"); imwrite(imgName, diffImage); 方法。这是代码。

findContours

我想在矩形中绑定差异部分。 import Foundation public class DateFormatter : NSDateFormatter{ public class func sharedFormatter() -> NSDateFormatter { // current thread's hash let threadHash = NSThread.currentThread().hash // check if a date formatter has already been created for this thread if let existingFormatter = NSThread.currentThread().threadDictionary[threadHash] as? NSDateFormatter{ // a date formatter has already been created, return that return existingFormatter }else{ // otherwise, create a new date formatter let dateFormatter = NSDateFormatter() // and store it in the threadDictionary (so that we can access it later on in the current thread) NSThread.currentThread().threadDictionary[threadHash] = dateFormatter return dateFormatter } } } 绘制的轮廓太多了。但我只需要一个特定的部分。我的差异图像为here

我想在所有五个刻度盘周围画一个矩形。

请指出正确的方向。

此致

3 个答案:

答案 0 :(得分:3)

我会搜索i索引的最高值,给出非黑色像素;那是正确的边界。

最低非黑色i是左边框。类似于j。

答案 1 :(得分:2)

你可以:

  1. 使用阈值对图像进行二值化。背景将为0。
  2. 使用findNonZero检索所有非0的点,即所有前景点。
  3. 在检索到的点上使用boundingRect
  4. 结果:

    enter image description here

    代码:

    #include <opencv2/opencv.hpp>
    using namespace cv;
    
    int main()
    {
        // Load image (grayscale)
        Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);
    
        // Binarize image
        Mat1b bin = img > 70;
    
        // Find non-black points
        vector<Point> points;
        findNonZero(bin, points);
    
        // Get bounding rect
        Rect box = boundingRect(points);
    
        // Draw (in color)
        Mat3b out;
        cvtColor(img, out, COLOR_GRAY2BGR);
        rectangle(out, box, Scalar(0,255,0), 3);
    
        // Show
        imshow("Result", out);
        waitKey();
    
        return 0;
    }
    

答案 2 :(得分:1)

查找轮廓,它会输出一组等高线std::vector<std::vector<cv::Point>让我们称之为contours

std::vector<cv::Point> all_points;
size_t points_count{0};
for(const auto& contour:contours){
    points_count+=contour.size();
    all_points.reserve(all_points);
    std::copy(contour.begin(), contour.end(),
              std::back_inserter(all_points));
}
auto bounding_rectnagle=cv::boundingRect(all_points);