Showing posts with label findContours. Show all posts
Showing posts with label findContours. 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



2/28/2022

cv2, findContours, find object and print x,y,w,h

Find white color object and print x,y,w,h

see example source code

..

#open image
img = cv2.imread("./test.jpg")

#binary
imgray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
ret, thresh = cv2.threshold(imgray, 127, 255, 0)

#contours
contours, hierarchy = cv2.findContours(thresh, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)

#print x,y,w,h for each object
w_list = []
h_list = []
for v in contours:
x,y,w,h = cv2.boundingRect(v)
w_list.append(w)
h_list.append(h)
print(x,y,w,h)

..

66 193 19 14
--
66 171 19 14
--



www.marearts.com

thank you.

🙇🏻‍♂️

10/25/2018

ValueError: too many values to unpack (expected 2), when you use "cv2.findContours"

check this tip!

before (error)
contours, _ = cv2.findContours(***, ***, ***)


after (solved)
_, contours, _ = cv2.findContours(***, ***, ***)


5/26/2018

Find contour example source code


Find Contour example source code


...
#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);

    cvtColor(img, img, CV_RGB2GRAY);
    img.setTo(0);
    rectangle(img, Rect(10, 10, 200, 200), CV_RGB(255, 255, 255), CV_FILLED);
    imshow("show1", 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);

    // iterate through all the top-level contours,
    // draw each connected component with its own random color
    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);
    }

    imshow("show2", dst);

    waitKey(0);

    return 0;
}
...

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);


...



4/26/2015

Background Subtraction and Blob labeling and FREAK feature extraction

This code is the source of this video.
https://www.youtube.com/watch?v=txOaulCPzSM



The source code included 2 separable routine.
One is blob labeling.
Another is FREAK feature extraction and draw.

Blob labeling is using MOG2 algorithm.
MOG2 is introduced in past on my blog.
Refer to this page.
http://study.marearts.com/search/label/MOG2
http://study.marearts.com/2014/04/opencv-study-background-subtractor-mog.html
By the way, this code included blur routine.
I thought low frequency image is more useful for background learning.
This rgb blur code on GPU mode is referenced from here.
http://study.marearts.com/2014/11/opencv-gpu-3-channel-blur-example.html

Another routine is FREAK feature extraction.
Firstly, find feature using FAST_GPU, and extract FREAK descriptor.
After extraction, 2 descriptor can compare same image or not.

This code is made for processing time check.
The process is enough to processing in real time, because image is resized and use GPU.

Hope helping to you.
Thank you.




...code start...

...code end...