logo
down
shadow

OpenCV: check if pixel is within bounding rectangle, separated by contour line


OpenCV: check if pixel is within bounding rectangle, separated by contour line

By : OmWhitney Rampersad
Date : November 22 2020, 02:42 PM
it helps some times
Ok let's assume I can get a connected component. How can I proceed then?
code :
#include <opencv2/opencv.hpp>
#include <vector>
using namespace std;
using namespace cv;


void separateAreas(const Rect& roi, const vector<Point>& points, vector<Point>& left, vector<Point>& right)
{
    left.clear();
    right.clear();

    // Temporary matrix
    // 0 : background pixels
    // 1 : boundary pixels
    // 2 : left pixels
    // 3 : right pixels
    Mat1b tmp(roi.height, roi.width + 2, uchar(0));

    // Shift points to roi origin, i.e tmp(0,1)
    vector<Point> pts(points);
    for (int i = 0; i < points.size(); ++i)
    {
        pts[i] -= roi.tl();

        // Draw boundary on tmp matrix
        tmp(pts[i] + Point(1,0)) = 1;
    }

    // Fill left area, seed top left point
    floodFill(tmp, Point(0, 0), Scalar(2));

    // Fill right area, seed top right point
    floodFill(tmp, Point(tmp.cols-1, 0), Scalar(3));

    // Find left and right points
    findNonZero(tmp.colRange(1, tmp.cols - 1) == 2, left);
    findNonZero(tmp.colRange(1, tmp.cols - 1) == 3, right);

    // Shift back
    for (int i = 0; i < left.size(); ++i)
    {
        left[i] += roi.tl();
    }
    for (int i = 0; i < right.size(); ++i)
    {
        right[i] += roi.tl();
    }
}


int main()
{
    Mat1b img = imread("path_to_image", IMREAD_GRAYSCALE);

    Mat3b res;
    cvtColor(img, res, COLOR_GRAY2BGR);

    vector<vector<Point>> contours;
    findContours(img.clone(), contours, RETR_LIST, CV_CHAIN_APPROX_NONE);

    for (int i = 0; i < contours.size(); ++i)
    {
        Rect roi = boundingRect(contours[i]);
        //rectangle(res, roi, Scalar(0,255,0));

        vector<Point> left, right;
        separateAreas(roi, contours[i], left, right);

        // Draw areas on res
        for (int j = 0; j < left.size(); ++j)
        {
            res(left[j]) = Vec3b(255,0,0); // Blue for left
        }
        for (int j = 0; j < right.size(); ++j)
        {
            res(right[j]) = Vec3b(0, 0, 255); // Red for right
        }
    }

    imshow("Image", img);
    imshow("Result", res);
    waitKey();

    return 0;
}


Share : facebook icon twitter icon
how to get bounding rectangle on both source and contour window?

how to get bounding rectangle on both source and contour window?


By : Gao
Date : March 29 2020, 07:55 AM
wish of those help Answered here. Code by sturkmen:
code :
 /**
 * @function generalContours_demo1.cpp
 * @brief Demo code to find contours in an image
 * @author OpenCV team
 */

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

using namespace cv;
using namespace std;

Mat src; Mat src_gray;
int thresh = 100;
int max_thresh = 255;
RNG rng(12345);

/// Function header
void thresh_callback(int, void* );

/**
 * @function main
 */
int main( int, char** argv )
{
  /// Load source image and convert it to gray
  src = imread( argv[1], 1 );

  /// Convert image to gray and blur it
  cvtColor( src, src_gray, COLOR_BGR2GRAY );
  blur( src_gray, src_gray, Size(3,3) );

  /// Create Window
  const char* source_window = "Source";
  namedWindow( source_window, WINDOW_AUTOSIZE );
  imshow( source_window, src );

  createTrackbar( " Threshold:", "Source", &thresh, max_thresh, thresh_callback );
  thresh_callback( 0, 0 );

  waitKey(0);
  return(0);
}

/**
 * @function thresh_callback
 */
void thresh_callback(int, void* )
{
  Mat threshold_output;
  vector<vector<Point> > contours;
  vector<Vec4i> hierarchy;

  /// Detect edges using Threshold
  threshold( src_gray, threshold_output, thresh, 255, THRESH_BINARY );
  /// Find contours
  findContours( threshold_output, contours, hierarchy, CV_RETR_TREE, CV_CHAIN_APPROX_SIMPLE, Point(0, 0) );

  /// Approximate contours to polygons + get bounding rects and circles
  vector<vector<Point> > contours_poly( contours.size() );
  vector<Rect> boundRect( contours.size() );
  vector<Point2f>center( contours.size() );
  vector<float>radius( contours.size() );

  for( size_t i = 0; i < contours.size(); i++ )
     { approxPolyDP( Mat(contours[i]), contours_poly[i], 3, true );
       boundRect[i] = boundingRect( Mat(contours_poly[i]) );
       minEnclosingCircle( contours_poly[i], center[i], radius[i] );
     }


  /// Draw polygonal contour + bonding rects + circles

  Mat src2 = src.clone(); //add this line
  Mat drawing = Mat::zeros( threshold_output.size(), CV_8UC3 );
  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( drawing, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );
       rectangle( drawing, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );
       circle( drawing, center[i], (int)radius[i], color, 2, 8, 0 );


       drawContours( src2, contours_poly, (int)i, color, 1, 8, vector<Vec4i>(), 0, Point() );//add this line
       rectangle( src2, boundRect[i].tl(), boundRect[i].br(), color, 2, 8, 0 );//add this line
       circle( src2, center[i], (int)radius[i], color, 2, 8, 0 );//add this line

     }

  /// Show in a window
  namedWindow( "Contours", WINDOW_AUTOSIZE );
  imshow( "Contours", drawing );
  imshow( "Source", src2 );//add this line
}
OpenCV: How to get the bounding box for each contour?

OpenCV: How to get the bounding box for each contour?


By : Hossein salamat
Date : March 29 2020, 07:55 AM
around this issue ** ~ Updated ~ ** Hi , I have a source file and i converted it to below picture , and i have a contour in my program , You can get the bounding box for each contour as:
code :
Rect box = boundingRect(contours[i]); 
rectangle(drawing, box, color);
Rect box = boundingRect(contours[i]); 
rectangle(drawing, box, color);
OpenCV - How to translate a pixel-following contour to vertex-following contour

OpenCV - How to translate a pixel-following contour to vertex-following contour


By : F. Rossi
Date : March 29 2020, 07:55 AM
To fix the issue you can do I managed to solve it by:
zooming the image x2 finding contours dividing the contour points by 2 and rounding up
OpenCV - How to find rectangle contour of a rectangle with round corner?

OpenCV - How to find rectangle contour of a rectangle with round corner?


By : 梁思前
Date : March 29 2020, 07:55 AM
Any of those help I'm trying to find the contour of a rectangle object with round corner in a image. I tried HoughLinesP and findContours, but did not achieve the desired result. , You need to find the bounding rectangle of the found contours.
code :
img = cv2.imread("image.png", -1)

gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

binary = cv2.bitwise_not(gray)

(_,contours,_) = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)

for contour in contours:
    (x,y,w,h) = cv2.boundingRect(contour)
    cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
How to change bounding rect values of contour in OpenCV Python?

How to change bounding rect values of contour in OpenCV Python?


By : Federico Moya
Date : March 29 2020, 07:55 AM
Hope that helps There's a misconception here, purely with Python that has nothing to do with OpenCV. Check the following code:
code :
>>> a = 5
>>> b = a
>>> a = 7
>>> a
7
>>> b
5
[i, j, k, l] = cv2.boundingRect(contours2[temp])
k = (x+w)-i 
bounding_boxes = []
for c in contours2:
    [x, y, w, h] = cv2.boundingRect(c)
    bounding_boxes.append([x, y, w, h])
bounding_boxes = []
for c in contours2:
    [x, y, w, h] = cv2.boundingRect(c)
    w = w*2
    bounding_boxes.append([x, y, w, h])
Related Posts Related Posts :
  • Qt event when anything changed on the window/screen + Screenshot
  • OpenGL Linker error, linking with uncompiled shader
  • Find 4 specific corner pixels and use them with warp perspective
  • Cin Execution Not Working (program.exe < filewithdata.txt)
  • cudaMallocManaged causes Access Violation
  • How to correctly read a value from stdin into a variable
  • Binary Search Tree Forgetting Every Node I Add
  • C++ Return Value from function not same as that value in function
  • Microsoft Visual Studio C++, OpenCV animation
  • C++ function pointer syntax. Why does (*) work but * not?
  • C++: Template class binary operator overloading - seg fault?
  • Passing buffer between two terminals (Named Pipe)
  • C++ parse sub-string to integer
  • Create stereo context for modern opengl
  • Memory leak, when using GLM
  • Get Control under cursor
  • Is this proper behavior? std::map iterator invalidation
  • 2D isometric engine - Math problems - Cube selection - diamond shape map
  • Open second window in Qt
  • Stack Overflow error with Vectors
  • Pure Virtual Friend Class
  • Object initialization syntax in C++
  • Variable undefined error
  • C++ tolower/toupper char pointer
  • Overhead with std::function
  • Is there a way to make a loop that get user input but doesn't stop if the user doesn't input anything?
  • OpenCV in cmake-based project: checking for contrib modules
  • shared_ptr vs unique_ptr uses in classes and children
  • MFC dialog Border padding changed after switching from VS2010 to 2012 or later
  • String rotator in C++ (bitwise rotation)
  • Custom sort vector of pair based on their values
  • Pointer to const overloaded member function
  • how to avoid this for-loop mess in c++?
  • Can the state of a standard C++ iostream manipulator be polled?
  • How to make sure a data type is as large as it needs to be in C++
  • Why is my first ofstream output in my else block missing the fill character?
  • Returning static/ normal arrays in recursion/another function
  • c++, why use const std::string & parameterName?
  • expression did not evaluate to a constant in C++ VS
  • Owner object that takes pre-created values ? Wrong design?
  • Cannot use Macro in a C++ constructor?
  • vector is loosing mat4 information
  • Invalid declarator before with map of struct?
  • std::initializer_list to return member variables returns incorrect values
  • Unable to use Boost + Qt in Mac
  • Passing template function and overload as function argument
  • non standard extension warning when searching in a vector of unique_ptrs
  • Qt Windows x64 build succeeds in IDE but not on the command line
  • condition_variable::wait_for method not returning - even after the timeout
  • boost::asio usage in self-contained class
  • CGAL triangulation with constraints changes points coords
  • How to resolve an ambiguous reference caused by a conflicting identifier from inline namespace
  • When UTF8 emoji character is removed from NSMutableString the conversion to std::string fails
  • XOR of two strings of 0s and 1s
  • geany: C++ Including libraries and headers
  • How can I combine an in place transformation, and a copy transformation?
  • error of the assigning unique ptr in another thread
  • SetArrayArgument, is it really the last or lenth?
  • What is the role of "&" and "*" on operator overloading?
  • C++ passing a nested unordered_map by reference and manipulating it
  • shadow
    Privacy Policy - Terms - Contact Us © animezone.co