Showing posts with label drawContours. Show all posts
Showing posts with label drawContours. Show all posts

4/17/2023

Python script to apply Canny edge detection and filter contours based on a dynamic threshold value, invert the image, and apply binary thresholding to create a mask on all images in a directory.

refer to code

 

.

import os
import cv2
from tqdm import tqdm
import numpy as np


# Path to input and output directories
input_dir = './background'
output_dir = './background_canny'

# Create the output directory if it doesn't exist
if not os.path.exists(output_dir):
os.makedirs(output_dir)

# Loop over all files in the input directory
for filename in tqdm(os.listdir(input_dir)):
if filename.endswith('.jpg') or filename.endswith('.png'):
# Load the input image
img = cv2.imread(os.path.join(input_dir, filename), cv2.IMREAD_GRAYSCALE)
# Apply Canny edge detection algorithm
edges = cv2.Canny(img, 100, 200)
# Find and draw the contours of the edge map
contours, hierarchy = cv2.findContours(edges, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
contours_filtered = []
threshold = int( min(0.1 * (img.shape[0]), 0.1 * (img.shape[1]) ) )
for cnt in contours:
if cv2.arcLength(cnt, True) >= threshold:
contours_filtered.append(cnt)
edges_contours = cv2.drawContours(np.zeros_like(img), contours_filtered, -1, 255, 1)

# Invert the image (black to white, white to black)
img_inv = cv2.bitwise_not(edges_contours)
# Apply binary thresholding to the image
thresh, img_binary = cv2.threshold(img_inv, 127, 255, cv2.THRESH_BINARY)

# Save the result in the output directory with the same file name
output_path = os.path.join(output_dir, filename)
cv2.imwrite(output_path, img_binary)


..




Thank you.

🙇🏻‍♂️

www.marearts.com



4/22/2019

OpenCV Simple Background Subtraction Example code


Step #1 
Simple background subtraction




code here

.



Step #2
remove noise + binary

code here

.

Step #3 & #4
Draw contour

Remove small area and draw rect



core here:

.



Thank you
☕️

12/29/2016

findContours, drawContours example code

The code is various example code for drawing contours.


...
namedWindow("show1", 0);
 namedWindow("threshold", 0);
 namedWindow("contours", 0);

 Mat img;
 img = imread("pattern.jpg");

 cvtColor(img, img, CV_RGB2GRAY);
 
 imshow("show1", img);


 threshold(img, img, 128, 255, CV_THRESH_BINARY);
 imshow("threshold", img);


 Mat dst = Mat::zeros(img.rows, img.cols, CV_8UC3);
 
 vector< vector< Point> > contours;
 vector< Vec4i> hierarchy;

 findContours(img.clone(), contours, hierarchy,
  RETR_CCOMP, CHAIN_APPROX_SIMPLE);

 
 //ex 1)
 drawContours(dst, contours, -1, CV_RGB(255,0,0), 1, 8, hierarchy);

 
 // iterate through all the top-level contours,
 // draw each connected component with its own random color
 //ex 2)
 int idx = 0;
 for (; idx >= 0; idx = hierarchy[idx][0])
 {
  Scalar color(rand() & 255, rand() & 255, rand() & 255);
  //drawContours(dst, contours, idx, color, FILLED, 8, hierarchy);
  drawContours(dst, contours, idx, color, 1, 8, hierarchy);
 }
 


 //ex3
 for (int i = 0; i < contours.size(); ++i)
 {
  
  for (int j = 0; j < contours[i].size() - 1; ++j)
  {
   line(dst, contours[i][j], contours[i][j + 1], CV_RGB(255, 0, 0), 1);
  }
  line(dst, contours[i][0], contours[i][contours[i].size()-1], CV_RGB(255, 0, 0), 1);
  
 }

 //ex4
 for (int i = 0; i < contours.size(); ++i)
 {

  Scalar color(rand() & 255, rand() & 255, rand() & 255);
  //drawContours(dst, contours, idx, color, FILLED, 8, hierarchy);
  drawContours(dst, contours, i, color, 1, 8, hierarchy);
 }
 

 //imshow("show3", img);
 imshow("contours", dst);


...



7/07/2016

OpenCV Drawing Example, (line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours)

line, circle, rectangle, ellipse, polyline, fillConvexPoly, putText, drawContours example source code!!.















...
//http://study.marearts.com/2016/06/opencv-mat-copyto-clone-roi-example-code.html

#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include <iostream>
#include <vector>

#ifdef _DEBUG               
#pragma comment(lib, "opencv_core331d.lib")       
#pragma comment(lib, "opencv_highgui331d.lib")    
#pragma comment(lib, "opencv_imgcodecs331d.lib")  
#pragma comment(lib, "opencv_objdetect331d.lib")  
#pragma comment(lib, "opencv_imgproc331d.lib")  
#pragma comment(lib, "opencv_videoio331d.lib")    
#else       
#pragma comment(lib, "opencv_core331.lib")       
#pragma comment(lib, "opencv_highgui331.lib")    
#pragma comment(lib, "opencv_imgcodecs331.lib")    
#pragma comment(lib, "opencv_objdetect331.lib")  
#pragma comment(lib, "opencv_imgproc331.lib")  
#pragma comment(lib, "opencv_videoio331.lib")    
#endif        


using namespace std;
using namespace cv;

int main()
{
    Mat img(500, 500, CV_8UC3);
    img.setTo(255);

    
    ///////////////////////////////////////////////////
    //line example
    cv::Point pt(300, 300);
    line(img, Point(10, 10), pt, CV_RGB(255, 0, 0), 2);
    line(img, Point(300, 10), Point(30, 300), Scalar(255, 0, 0), 2);
    ///////////////////////////////////////////////////


    ///////////////////////////////////////////////////
    //Circle example
    circle(img, Point(250, 250), 100, CV_RGB(0, 255, 0), 3);
    cv::Point center(400, 400);
    circle(img, center, 300, Scalar(255, 255, 0), 10);
    circle(img, Point(40, 40), 10, Scalar(255, 0, 0), -1);
    ///////////////////////////////////////////////////


    ///////////////////////////////////////////////////
    //rectangle example
    rectangle(img, Rect(10, 10, 200, 200), CV_RGB(255, 0, 0), 2);
    rectangle(img, Rect(Point(40, 40), Point(400, 400)), Scalar(255, 0, 0), 10);
    ///////////////////////////////////////////////////


    /////////////////////////////////////////////////// 
    //ellipse example 1
    ellipse(img, Point(100, 100), Size(100, 50), 0, 0, 360, CV_RGB(255, 0, 0));
    ellipse(img, Point(100, 100), Size(100, 50), 30, 0, 360, CV_RGB(0, 255, 0));
    ellipse(img, Point(100, 100), Size(100, 50), 60, 0, 360, CV_RGB(0, 0, 255));

    ellipse(img, Point(300, 300), Size(100, 50), 0, 0, 180, CV_RGB(255, 0, 0));
    ellipse(img, Point(300, 300), Size(100, 50), 30, 0, 270, CV_RGB(0, 255, 0));
    ellipse(img, Point(300, 300), Size(100, 50), 60, 0, 360, CV_RGB(0, 0, 255));
    ///////////////////////////////////////////////////

    /////////////////////////////////////////////////// 
    //ellipse example 2
    RotatedRect rRect = RotatedRect(Point2f(300, 300), Size2f(300, 100), 30);
    ellipse(img, rRect, CV_RGB(255, 0, 0));

    //draw rect and inside rect in RotatedRect
    Point2f vertices[4];
    rRect.points(vertices);
    for (int i = 0; i < 4; i++)
        line(img, vertices[i], vertices[(i + 1) % 4], Scalar(0, 255, 0));

    Rect brect = rRect.boundingRect();
    rectangle(img, brect, Scalar(255, 0, 0));
    ///////////////////////////////////////////////////
    

    /*
    ///////////////////////////////////////////////////
    //polylines example 1 
    vector< Point> contour;
    contour.push_back(Point(50, 50));
    contour.push_back(Point(300, 50));
    contour.push_back(Point(350, 200));
    contour.push_back(Point(300, 150));
    contour.push_back(Point(150, 350));
    contour.push_back(Point(100, 100));

    const Point *pts = (const cv::Point*) Mat(contour).data;
    int npts = Mat(contour).rows;

    std::cout << "Number of polygon vertices: " << npts << std::endl;
    // draw the polygon 
    polylines(img, &pts, &npts, 1, false, Scalar(0, 255, 0));

    //polylines example 2 
    contour.clear();
    contour.push_back(Point(400, 400));
    contour.push_back(Point(250, 250));
    contour.push_back(Point(50, 300));

    pts = (const cv::Point*) Mat(contour).data;
    npts = Mat(contour).rows;
    polylines(img, &pts, &npts, 1, true, Scalar(255, 0, 0));
    ///////////////////////////////////////////////////
    */


    /*
    ///////////////////////////////////////////////////
    //fillConvexPoly example 1 
    cv::Point ptss[4];
    ptss[0] = cv::Point(100, 100);
    ptss[1] = cv::Point(150, 200);
    ptss[2] = cv::Point(300, 300);
    ptss[3] = cv::Point(400, 100);

    cv::fillConvexPoly(img, ptss, 4, cv::Scalar(0, 0, 200));
    ///////////////////////////////////////////////////
    */

    /*
    ///////////////////////////////////////////////////
    //textout example 1
    char TestStr[100];
    sprintf_s(TestStr, "total time : %lf sec", 0.001);
    putText(img, TestStr, Point(10, 250), CV_FONT_NORMAL, 1, Scalar(0, 0, 0), 1, 1); //OutImg is Mat class;
    ///////////////////////////////////////////////////
    */

    
    imshow("show0", img);
    waitKey(0);

    return 0;
}
...