草庐IT

c++ - OpenCV 投资返回率错误

coder 2024-02-15 原文

我正在尝试制作一个程序,通过在图像上滑动 ROI 并将 ROI 与模板进行比较来识别模式,它将比较 ROI 和模板的像素值,每次将计数器加 1像素匹配,然后我将计数器与阈值进行比较,如果它通过一个矩形将被绘制,如果没有,它将继续在图像中滑动,如果我在其上运行调试器,它显示在图像中滑动时没有错误,但如果我正常运行它,它会抛出下一个异常:

OpenCV Error: Assertion failed (0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows) in Mat, file /home/abuild/rpmbuild/BUILD/opencv-2.4.6.1/modules/core/src/matrix.cpp, line 323
terminate called after throwing an instance of 'cv::Exception'
what():  /home/abuild/rpmbuild/BUILD/opencv-2.4.6.1/modules/core/src/matrix.cpp:323: error: (-215) 0 <= roi.x && 0 <= roi.width && roi.x + roi.width <= m.cols && 0 <= roi.y && 0 <= roi.height && roi.y + roi.height <= m.rows in function Mat

我在下面留下代码:

#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include <opencv2/core/core.hpp>
#include <opencv2/imgproc/imgproc.hpp>


using namespace std;
using namespace cv;

Mat         iOrig;                          //imagen que se analizara
Mat         patron;                         //patron buscado
Point       corner1,corner2;                //esquinas del ROI
bool        tresholdpass;                   //boolean returned by comparar()
Rect        box;                            //rectangulo usado para crear el ROI
float       porcentaje;                     //distancia a recorrer que sera dada por el tamano de la imagen muestra para el patron
float       treshold;                       //treshold que debera ser superado para que se considere similar o igual al patron
float       valpx;                          //valor almacenado en el pixel comparado
float       contTreshold;                   //contador a comparar contra el porcentaje requerido para considerarse como patron encontrado
float       totpxpat;                       //cantidad de pixeles de la imagen muestra del patron
float       porctreshold;                   //porcentaje representativo para considerar que se encontro el patron en esa ROI

bool comparar(Mat region, Mat patron){

    int i=0;
    int j=0;
    contTreshold=0;

    for (i=0;i<patron.cols;i++){
        for (j=0;j<patron.rows;j++){
            Point a(i,j);
            if(abs(region.at<float>(a))==abs(patron.at<float>(a))){
            //se compara el contenido de el ROI y el patron en un punto
                contTreshold++;             //en caso de ser cierto, el contador aumenta en 1
            }
        }

    }
    totpxpat = patron.rows*patron.cols;     //se cuentan la cantidad de pixeles dado columnas*renglones
    porctreshold = 0.8;                     //el porcentaje que se usara para el treshold
    treshold = totpxpat * porctreshold;     //el treshold que determinara si se cumple el porcentaje de la imagen
                                        //para saber si cumple el patron o no, en caso de q se supere, retornara verdadero
                                        //en caso de que no se supere retornara falso y se elegira otro ROI para analizar
    if (contTreshold>treshold){
        return true;
    }else{
        return false;
    }
}

int main() {

    namedWindow("imagen");
    namedWindow("segmento");

    iOrig = imread( "/home/diego/Downloads/figuras.jpg",CV_LOAD_IMAGE_GRAYSCALE );
    patron = imread("/home/diego/Downloads/patron.jpg",CV_LOAD_IMAGE_GRAYSCALE);

    imshow("imagen",iOrig);
    imshow("segmento",patron);
    corner1.x = 1;
    corner1.y = 1;
    corner2.x = patron.cols;
    corner2.y = patron.rows;


    porcentaje = (int)patron.cols * 0.05;

    while (corner2.x<iOrig.rows-(patron.rows*2)){
        while(corner2.y<iOrig.cols-(patron.cols*2)){
            box.width = abs (corner1.x-corner2.x)+1;
            box.height = abs (corner1.y - corner2.y)+1;
            box.x = min(corner1.x, corner2.x);
            box.y = min(corner1.y, corner2.y);


        //se crea una imagen de la region de interes seleccionada apartir de las 2 esquinas de la ROI
            Mat     region(iOrig,box);              //region de interes que sera comparada

        //se manda a comparar el ROI con el patron
            tresholdpass=comparar(region,patron);
            if (tresholdpass == true){
                Mat local_img = iOrig.clone();
                rectangle(local_img,corner1,corner2,Scalar(0,0,255));
                imshow("imagen",local_img);

            }
            corner1.x+=porcentaje;
            corner2.x+=porcentaje;
        }
        corner1.y+=porcentaje;
        corner2.y+=porcentaje;
    }

    while (char(waitKey(1))!= 'q'){}
    return 0;
}

由于信誉原因,我无法上传我正在使用的图像...但原始图像为 800 x 450,图像中搜索的模板为 131 x 132

抱歉,我的代码中的注释是西类牙语,英语不是我的母语,正如您现在猜到的那样,我真的不知道我的错误在哪里但是......我希望它很简单提前谢谢你!

最佳答案

这意味着您正试图将 ROI 区域移出图像平面。您应该确保 ROI 区域在图像平面内,以避免崩溃。

对于你的情况,你可以这样做:

// check the box within the image plane
if (0 <= box.x
    && 0 <= box.width
    && box.x + box.width <= iOrig.cols
    && 0 <= box.y
    && 0 <= box.height
    && box.y + box.height <= iOrig.rows){
    // box within the image plane
    Mat region(iOrig, box);
}
else{
    // box out of image plane, do something...
}

关于c++ - OpenCV 投资返回率错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29712057/

有关c++ - OpenCV 投资返回率错误的更多相关文章

  1. ruby-on-rails - Rails 常用字符串(用于通知和错误信息等) - 2

    大约一年前,我决定确保每个包含非唯一文本的Flash通知都将从模块中的方法中获取文本。我这样做的最初原因是为了避免一遍又一遍地输入相同的字符串。如果我想更改措辞,我可以在一个地方轻松完成,而且一遍又一遍地重复同一件事而出现拼写错误的可能性也会降低。我最终得到的是这样的:moduleMessagesdefformat_error_messages(errors)errors.map{|attribute,message|"Error:#{attribute.to_s.titleize}#{message}."}enddeferror_message_could_not_find(obje

  2. ruby - 为什么 4.1%2 使用 Ruby 返回 0.0999999999999996?但是 4.2%2==0.2 - 2

    为什么4.1%2返回0.0999999999999996?但是4.2%2==0.2。 最佳答案 参见此处:WhatEveryProgrammerShouldKnowAboutFloating-PointArithmetic实数是无限的。计算机使用的位数有限(今天是32位、64位)。因此计算机进行的浮点运算不能代表所有的实数。0.1是这些数字之一。请注意,这不是与Ruby相关的问题,而是与所有编程语言相关的问题,因为它来自计算机表示实数的方式。 关于ruby-为什么4.1%2使用Ruby返

  3. ruby-on-rails - 如何优雅地重启 thin + nginx? - 2

    我的瘦服务器配置了nginx,我的ROR应用程序正在它们上运行。在我发布代码更新时运行thinrestart会给我的应用程序带来一些停机时间。我试图弄清楚如何优雅地重启正在运行的Thin实例,但找不到好的解决方案。有没有人能做到这一点? 最佳答案 #Restartjustthethinserverdescribedbythatconfigsudothin-C/etc/thin/mysite.ymlrestartNginx将继续运行并代理请求。如果您将Nginx设置为使用多个上游服务器,例如server{listen80;server

  4. ruby-on-rails - 迷你测试错误 : "NameError: uninitialized constant" - 2

    我遵循MichaelHartl的“RubyonRails教程:学习Web开发”,并创建了检查用户名和电子邮件长度有效性的测试(名称最多50个字符,电子邮件最多255个字符)。test/helpers/application_helper_test.rb的内容是:require'test_helper'classApplicationHelperTest在运行bundleexecraketest时,所有测试都通过了,但我看到以下消息在最后被标记为错误:ERROR["test_full_title_helper",ApplicationHelperTest,1.820016791]test

  5. ruby - 检查字符串是否包含散列中的任何键并返回它包含的键的值 - 2

    我有一个包含多个键的散列和一个字符串,该字符串不包含散列中的任何键或包含一个键。h={"k1"=>"v1","k2"=>"v2","k3"=>"v3"}s="thisisanexamplestringthatmightoccurwithakeysomewhereinthestringk1(withspecialcharacterslike(^&*$#@!^&&*))"检查s是否包含h中的任何键的最佳方法是什么,如果包含,则返回它包含的键的值?例如,对于上面的h和s的例子,输出应该是v1。编辑:只有字符串是用户定义的。哈希将始终相同。 最佳答案

  6. ruby-on-rails - 如何在 Rails View 上显示错误消息? - 2

    我是rails的新手,想在form字段上应用验证。myviewsnew.html.erb.....模拟.rbclassSimulation{:in=>1..25,:message=>'Therowmustbebetween1and25'}end模拟Controller.rbclassSimulationsController我想检查模型类中row字段的整数范围,如果不在范围内则返回错误信息。我可以检查上面代码的范围,但无法返回错误消息提前致谢 最佳答案 关键是您使用的是模型表单,一种显示ActiveRecord模型实例属性的表单。c

  7. 使用 ACL 调用 upload_file 时出现 Ruby S3 "Access Denied"错误 - 2

    我正在尝试编写一个将文件上传到AWS并公开该文件的Ruby脚本。我做了以下事情:s3=Aws::S3::Resource.new(credentials:Aws::Credentials.new(KEY,SECRET),region:'us-west-2')obj=s3.bucket('stg-db').object('key')obj.upload_file(filename)这似乎工作正常,除了该文件不是公开可用的,而且我无法获得它的公共(public)URL。但是当我登录到S3时,我可以正常查看我的文件。为了使其公开可用,我将最后一行更改为obj.upload_file(file

  8. ruby-on-rails - 错误 : Error installing pg: ERROR: Failed to build gem native extension - 2

    我克隆了一个rails仓库,我现在正尝试捆绑安装背景:OSXElCapitanruby2.2.3p173(2015-08-18修订版51636)[x86_64-darwin15]rails-v在您的Gemfile中列出的或native可用的任何gem源中找不到gem'pg(>=0)ruby​​'。运行bundleinstall以安装缺少的gem。bundleinstallFetchinggemmetadatafromhttps://rubygems.org/............Fetchingversionmetadatafromhttps://rubygems.org/...Fe

  9. ruby - #之间? Cooper 的 *Beginning Ruby* 中的错误或异常 - 2

    在Cooper的书BeginningRuby中,第166页有一个我无法重现的示例。classSongincludeComparableattr_accessor:lengthdef(other)@lengthother.lengthenddefinitialize(song_name,length)@song_name=song_name@length=lengthendenda=Song.new('Rockaroundtheclock',143)b=Song.new('BohemianRhapsody',544)c=Song.new('MinuteWaltz',60)a.betwee

  10. ruby-on-rails - 每次我尝试部署时,我都会得到 - (gcloud.preview.app.deploy) 错误响应 : [4] DEADLINE_EXCEEDED - 2

    我是Google云的新手,我正在尝试对其进行首次部署。我的第一个部署是RubyonRails项目。我基本上是在关注thisguideinthegoogleclouddocumentation.唯一的区别是我使用的是我自己的项目,而不是他们提供的“helloworld”项目。这是我的app.yaml文件runtime:customvm:trueentrypoint:bundleexecrackup-p8080-Eproductionconfig.ruresources:cpu:0.5memory_gb:1.3disk_size_gb:10当我转到我的项目目录并运行gcloudprevie

随机推荐