Skip to content

Instantly share code, notes, and snippets.

@enpe
Created July 12, 2015 19:29
Show Gist options
  • Save enpe/89630565044c87198100 to your computer and use it in GitHub Desktop.
Save enpe/89630565044c87198100 to your computer and use it in GitHub Desktop.
OpenCV bug 4448: minimal example
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <iostream>
#include <vector>
int main()
{
using namespace std;
using namespace cv;
// Test data.
int lineWidth = 1; // Unexpected behavior disappears if >1.
Scalar color( 255, 255, 255, 255 );
Mat mask = 255 * Mat::ones(700, 700, CV_8UC1);
rectangle( mask, Point( 10, 10 ), Point( 200, 200 ), 0, -1 );
Point br( mask.size().width - 1, mask.size().height - 1 );
line( mask, Point( 0, 0 ), br, Scalar::all( 0 ), lineWidth );
line( mask, Point( 0, br.y ), Point( br.x, 0 ), Scalar::all( 0 ), lineWidth );
circle( mask, Point( 350, 350 ), 100, 0, lineWidth );
// mask = ( 255 * cv::Mat::ones( mask.size(), mask.type() ) ) - mask; // Invert the mask.
// Detect contours.
vector< vector< Point > > contours;
vector< Vec4i > hierarchy;
int mode = // Uncomment one of the lines below for testing.
// RETR_EXTERNAL;
// RETR_LIST;
RETR_CCOMP;
// RETR_TREE;
// RETR_FLOODFILL;
int method =
CHAIN_APPROX_NONE;
// CHAIN_APPROX_SIMPLE;
// CHAIN_APPROX_TC89_L1;
// CHAIN_APPROX_TC89_KCOS;
findContours( mask.clone(), contours, hierarchy, mode, method, Point( 0, 0 ) );
// Draw the contours and display the results.
Mat contoursImg = Mat::zeros( mask.size(), CV_8UC3 );
RNG rng;
for ( size_t i = 0; i < contours.size(); ++i )
{
Scalar color = Scalar( rng.uniform( 0, 255 ), rng.uniform( 0, 255 ), rng.uniform( 0, 255 ) );
drawContours( contoursImg, contours, (int)i, color, 1, 8, hierarchy, 0, Point() );
}
cv::Rect magnification( 255, 255, 50, 50 );
cv::Size dsize( 400, 400 );
cv::Mat mask_magnified, contours_magnified;
cv::resize( mask( magnification ), mask_magnified, dsize, 0, 0, INTER_NEAREST );
cv::resize( contoursImg( magnification ), contours_magnified, dsize, 0, 0, INTER_NEAREST );
cv::Mat3b maskImg;
cvtColor( mask, maskImg, COLOR_GRAY2BGR );
rectangle( maskImg, magnification, cv::Scalar( 0, 0, 255 ), 0 );
rectangle( contoursImg, magnification, cv::Scalar( 0, 0, 255 ), 0 );
cv::imwrite( "00_mask.png", maskImg );
cv::imwrite( "01_mask_magnified.png", mask_magnified );
cv::imwrite( "02_contours.png", contoursImg );
cv::imwrite( "03_contours_magnified.png", contours_magnified );
namedWindow( "mask", WINDOW_AUTOSIZE );
namedWindow("contours", WINDOW_AUTOSIZE );
imshow( "mask", maskImg );
imshow( "contours", contoursImg );
waitKey( 0 );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment