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



5/27/2018

AdaptiveThreshold test code in opencv


...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.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")  
#pragma comment(lib, "opencv_cudaarithm331d.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")
#pragma comment(lib, "opencv_cudaarithm331.lib")
#endif        


using namespace std;
using namespace cv;



int main(int, char)
{

    namedWindow("img", 0);
    namedWindow("threshold", 0);
    namedWindow("mean_thres", 0);
    namedWindow("gauss_thres", 0);


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

    Mat gray, binary, binary1, binary2;
    cvtColor(img, gray, CV_RGB2GRAY);

    threshold(gray, binary, 128, 255, CV_THRESH_BINARY);
    adaptiveThreshold(gray, binary1, 255, ADAPTIVE_THRESH_MEAN_C, THRESH_BINARY, 5, 5);
    adaptiveThreshold(gray, binary2, 255, ADAPTIVE_THRESH_GAUSSIAN_C, THRESH_BINARY, 5, 5);


    imshow("img", img);

    imshow("threshold", binary);
    imshow("mean_thres", binary1);
    imshow("gauss_thres", binary2);


    waitKey(0);

    return 0;
}


...

result

Threshold demo in OpenCV

Threshold test for
0: Binary
1: Binary Inverted
2: Threshold Truncated
3: Threshold to Zero
4: Threshold to Zero Inverted

...
#include "opencv2/opencv.hpp"
#include "opencv2/highgui.hpp"
#include "opencv2/cudaarithm.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")  
#pragma comment(lib, "opencv_cudaarithm331d.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")
#pragma comment(lib, "opencv_cudaarithm331.lib")
#endif        


using namespace std;
using namespace cv;


int threshold_value = 0;
int threshold_type = 3;;
int const max_value = 255;
int const max_type = 4;
int const max_BINARY_value = 255;

Mat src, src_gray, dst;
char* window_name = "Threshold Demo";

char* trackbar_type = "Type: \n 0: Binary \n 1: Binary Inverted \n 2: Truncate \n 3: To Zero \n 4: To Zero Inverted";
char* trackbar_value = "Value";

/// Function headers
void Threshold_Demo(int, void*);



void main()
{
    /// Load an image
    src = imread("blade.jpg", 1);

    /// Convert the image to Gray
    cvtColor(src, src_gray, CV_BGR2GRAY);

    /// Create a window to display results
    namedWindow(window_name, 0);
    resizeWindow(window_name, 500, 500);

    /// Create Trackbar to choose type of Threshold
    printf("%s", trackbar_type);
    createTrackbar(trackbar_type,
        window_name, &threshold_type,
        max_type, Threshold_Demo);

    createTrackbar(trackbar_value,
        window_name, &threshold_value,
        max_value, Threshold_Demo);

    /// Call the function to initialize
    Threshold_Demo(0, 0);

    //origin 
    namedWindow("origin", 0);
    imshow("origin", src);

    /// Wait until user finishes program
    while (true)
    {
        int c;
        c = waitKey(20);
        if ((char)c == 27)
        {
            break;
        }
    }

}


void Threshold_Demo(int, void*)
{
    // 0: Binary
    //1: Binary Inverted
    //2: Threshold Truncated
    //3: Threshold to Zero
    //4: Threshold to Zero Inverted


    threshold(src_gray, dst, threshold_value, max_BINARY_value, threshold_type);

    imshow(window_name, dst);
}

...


4/14/2017

Otzu binary simple example


< gist code >

< /gist code >




#Tags
AdaptiveThreshold, Threshold, OTZU, GaussianBlur

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...