En este post comento el código para obtener la bounding box de una imagen en OpenCV 2.1. ¿Que es un Bounding-Box? Es un término que hace referencia al rectángulo mas pequeño que encierra completamente todos los puntos píxel cuya profundidad no son completamente 0, es decir, no son negros.

Esto puede ser utilizado para descartar regiones de la imagen que no necesitamos procesar en un algoritmo. ¿Qué ocurre si la imagen tienen ruido? Pues que habrá muchos bounding-box en las zonas de ruido. Por ello, hay que obtener el contorno de mayor área, como muestro en el código más abajo.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
/********************************
*      David López Fernández    * 
*    Ingeniero en Informática   *
*        i52lofed@uco.es        *
********************************/
#ifdef _CH_
#pragma package <opencv>
#endif
 
#define CV_NO_BACKWARD_COMPATIBILITY
 
#include "cv.h"
#include "highgui.h"
#include <stdio.h>
#include <limits>
 
using namespace cv;
using namespace std;
 
Rect boundingRect ( const vector<cv::Point> & points )
{
	// Points initialization
	Point min ( std::numeric_limits<int>::max(),std::numeric_limits<int>::max() );
	Point max ( std::numeric_limits<int>::min(),std::numeric_limits<int>::min() );
 
	// Getting bounding box coordinates
	for ( unsigned int i=0;i<points.size();i++ ) {
		if ( points[i].x > max.x ) max.x=points[i].x;
		if ( points[i].x < min.x ) min.x=points[i].x;
 
		if ( points[i].y > max.y ) max.y=points[i].y;
		if ( points[i].y < min.y ) min.y=points[i].y;
	}
 
	return Rect ( min.x,min.y,max.x-min.x+1,max.y-min.y+1 );
} 
 
int main(int argc, char** argv)
{
	// Declares a vector of vectors for store the contours
	vector<vector<Point> > v;
 
	Mat originalimage;
	Mat image;
 
	// Loads the original image
	originalimage = imread("original.ppm");
	// Converts original image to an 8UC1 image
	cvtColor(originalimage, image, CV_BGR2GRAY);
 
	// Finds contours
	findContours(image,v,CV_RETR_LIST,CV_CHAIN_APPROX_NONE);
 
	// Finds the contour with the largest area
	int area = 0;
	int idx;
	for(int i=0; i<v.size();i++) {
		if(area < v[i].size()) {
			idx = i; 
                        area = v[i].size();
                }
	}
 
	// Calculates the bounding rect of the largest area contour
	Rect rect = boundingRect(v[idx]);
	Point pt1, pt2;
	pt1.x = rect.x;
	pt1.y = rect.y;
	pt2.x = rect.x + rect.width;
	pt2.y = rect.y + rect.height;
	// Draws the rect in the original image and show it
	rectangle(originalimage, pt1, pt2, CV_RGB(255,0,0), 1);
 
	cvNamedWindow( "Ejemplo", CV_WINDOW_AUTOSIZE );
	imshow("Ejemplo", originalimage );
	cvWaitKey(0);
 
	cvDestroyWindow("Ejemplo" );
 
}
Tagged with:
 

2 Responses to Bounding box de una imagen en OpenCV 2.1

  1. ss23 dice:


    for(int i=0; i<v.size();i++) {
    if(area < v[i].size())
    idx = i;
    }

    should probably be more like

    for (int j = 0; j < v.size(); j++) {
    if (area < v[j].size()) {
    area = v[j].size();
    idx = j;
    }
    }

Deja un comentario

Tu dirección de correo electrónico no será publicada. Los campos necesarios están marcados *

*

Puedes usar las siguientes etiquetas y atributos HTML: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="" highlight="">