keywords: DeepLearning, OpenCV

Env

Install opencv-python

Install numpy using pip:

py -3 -m pip install numpy

Install cv2 using pip:

pip install opencv-python

How do I install opencv using pip?
https://stackoverflow.com/a/62460856/1645289

Common Cases

Read and Write Image
using namespace cv;
// Capture the Image from the webcam
VideoCapture cap(0);

// Get the frame
Mat save_img; cap >> save_img;

if(save_img.empty())
{
  std::cerr << "Something is wrong with the webcam, could not get frame." << std::endl;
}
// Save the frame into a file
imwrite("test.jpg", save_img); // A JPG FILE IS BEING SAVED
// Reading the image file from a given location in system
Mat img = imread("..path\\abcd.jpg");

// writing the image to a defined location as JPEG
bool check = imwrite("..path\\MyImage.jpg", img);

Origin:
https://stackoverflow.com/a/13708531/1645289

Convert to Gray Scale
#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

Origin:
https://stackoverflow.com/a/10346021/1645289

Change Contrast
// Read the image file
Mat image = imread("D:/My OpenCV Website/Christmas.jpg");

// Check for failure
if (image.empty())
{
    cout << "Could not open or find the image" << endl;
    cin.get(); //wait for any key press
    return -1;
}

Mat imageContrastHigh2;
image.convertTo(imageContrastHigh2, -1, 2, 0); //increase the contrast by 2

Mat imageContrastHigh4;
image.convertTo(imageContrastHigh4, -1, 4, 0); //increase the contrast by 4

Mat imageContrastLow0_5;
image.convertTo(imageContrastLow0_5, -1, 0.5, 0); //decrease the contrast by 0.5

Mat imageContrastLow0_25;
image.convertTo(imageContrastLow0_25, -1, 0.25, 0); //decrease the contrast by 0.25

Origin: Change Contrast
https://www.opencv-srf.com/2018/02/change-contrast-of-images-and-videos.html

Median Filtering Denoise

Single frame:

#include <opencv2/opencv.hpp>

using namespace cv;

int main()
{
    Mat img = imread("test.jpg");
    Mat grayImg;
    cvtColor(img, grayImg, COLOR_BGR2GRAY);
    Mat filteredImg;
    medianBlur(grayImg, filteredImg, 5);

    imshow("Original image", grayImg);
    imshow("Filtered image", filteredImg);
    waitKey(0);
    destroyAllWindows();

    return 0;
}

Origin: Median Filtering of the Image using OpenCV
https://lindevs.com/median-filtering-of-the-image-using-opencv

Batch frames:

#include <opencv2/opencv.hpp>
#include <iostream>
#include <random>

using namespace std;
using namespace cv;

int computeMedian(vector<int> elements)
{
    nth_element(elements.begin(), elements.begin() + elements.size() / 2, elements.end());

    //sort(elements.begin(),elements.end());
    return elements[elements.size() / 2];
}

cv::Mat compute_median(std::vector<cv::Mat> vec)
{
    // Note: Expects the image to be CV_8UC3
    cv::Mat medianImg(vec[0].rows, vec[0].cols, CV_8UC3, cv::Scalar(0, 0, 0));

    for (int row = 0; row < vec[0].rows; row++)
    {
        for (int col = 0; col < vec[0].cols; col++)
        {
            std::vector<int> elements_B;
            std::vector<int> elements_G;
            std::vector<int> elements_R;

            for (int imgNumber = 0; imgNumber < vec.size(); imgNumber++)
            {
                int B = vec[imgNumber].at<cv::Vec3b>(row, col)[0];
                int G = vec[imgNumber].at<cv::Vec3b>(row, col)[1];
                int R = vec[imgNumber].at<cv::Vec3b>(row, col)[2];

                elements_B.push_back(B);
                elements_G.push_back(G);
                elements_R.push_back(R);
            }

            medianImg.at<cv::Vec3b>(row, col)[0] = computeMedian(elements_B);
            medianImg.at<cv::Vec3b>(row, col)[1] = computeMedian(elements_G);
            medianImg.at<cv::Vec3b>(row, col)[2] = computeMedian(elements_R);
        }
    }
    return medianImg;
}

int main(int argc, char const* argv[])
{
    std::string video_file;
    // Read video file
    if (argc > 1)
    {
        video_file = argv[1];
    }
    else
    {
        video_file = "video.mp4";
    }

    VideoCapture cap(video_file);
    if (!cap.isOpened())
        cerr << "Error opening video file\n";

    // Randomly select 25 frames
    default_random_engine generator;
    uniform_int_distribution<int>distribution(0, cap.get(CAP_PROP_FRAME_COUNT));

    vector<Mat> frames;
    Mat frame;

    for (int i = 0; i < 25; i++)
    {
        int fid = distribution(generator);
        cap.set(CAP_PROP_POS_FRAMES, fid);
        Mat frame;
        cap >> frame;
        if (frame.empty())
            continue;
        frames.push_back(frame);
    }
    // Calculate the median along the time axis
    Mat medianFrame = compute_median(frames);

    // Display median frame
    imshow("frame", medianFrame);
    waitKey(0);
}

Simple Background Estimation in Videos using OpenCV (C++/Python)
https://learnopencv.com/simple-background-estimation-in-videos-using-opencv-c-python/

CLAHE (Histogram Equalization)

Method 1st:

import numpy as np
import cv2 as cv
 
img = cv.imread('tsukuba_l.png', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
 
# create a CLAHE object (Arguments are optional).
clahe = cv.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl1 = clahe.apply(img)
 
cv.imwrite('clahe_2.jpg',cl1)

Histograms - 2: Histogram Equalization
https://docs.opencv.org/4.11.0/d5/daf/tutorial_py_histogram_equalization.html
How can I adjust contrast in OpenCV in C?
https://stackoverflow.com/a/35764666/1645289

Method 2nd:

img = cv2.imread(img_path, cv2.IMREAD_COLOR)
img = cv2.cvtColor(img, cv2.COLOR_RGB2Lab)

#configure CLAHE
clahe = cv2.createCLAHE(clipLimit=10, tileGridSize=(8,8))

#0 to 'L' channel, 1 to 'a' channel, and 2 to 'b' channel
img[:,:,0] = clahe.apply(img[:,:,0])

img = cv2.cvtColor(img, cv2.COLOR_Lab2RGB)

cv2.imshow("image", img)
cv2.waitKey(0)
cv2.destroyAllWindows()

How to apply CLAHE on RGB color images
https://stackoverflow.com/a/47370615/1645289

Thresholding (Binarization)
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
 
img = cv.imread('sudoku.png', cv.IMREAD_GRAYSCALE)
assert img is not None, "file could not be read, check with os.path.exists()"
img = cv.medianBlur(img,5)
 
ret,th1 = cv.threshold(img,127,255,cv.THRESH_BINARY)
th2 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_MEAN_C,\
            cv.THRESH_BINARY,11,2)
th3 = cv.adaptiveThreshold(img,255,cv.ADAPTIVE_THRESH_GAUSSIAN_C,\
            cv.THRESH_BINARY,11,2)
 
titles = ['Original Image', 'Global Thresholding (v = 127)',
            'Adaptive Mean Thresholding', 'Adaptive Gaussian Thresholding']
images = [img, th1, th2, th3]
 
for i in range(4):
    plt.subplot(2,2,i+1),plt.imshow(images[i],'gray')
    plt.title(titles[i])
    plt.xticks([]),plt.yticks([])
plt.show()

Image Thresholding
https://docs.opencv.org/4.11.0/d7/d4d/tutorial_py_thresholding.html

Enhancing contrast in color images
import cv2
import numpy as np

img = cv2.imread('flower.jpg', 1)
# converting to LAB color space
lab= cv2.cvtColor(img, cv2.COLOR_BGR2LAB)
l_channel, a, b = cv2.split(lab)

# Applying CLAHE to L-channel
# feel free to try different values for the limit and grid size:
clahe = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8,8))
cl = clahe.apply(l_channel)

# merge the CLAHE enhanced L-channel with the a and b channel
limg = cv2.merge((cl,a,b))

# Converting image from LAB Color model to BGR color spcae
enhanced_img = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)

# Stacking the original image with the enhanced image
result = np.hstack((img, enhanced_img))
cv2.imshow('Result', result)

Origin:
https://stackoverflow.com/a/41075028/1645289

Image Enhancement Techniques using OpenCV – Python
https://www.geeksforgeeks.org/image-enhancement-techniques-using-opencv-python/

Enhancing edge contrast in grayscale images
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include <opencv2/photo.hpp>

using namespace cv;
using cv::CLAHE;

int main(int argc, char** argv) {
    Mat srcImage = imread("D:\\H1o8X.png", IMREAD_GRAYSCALE);
    imshow("src", srcImage);

    Mat denoised;

    fastNlMeansDenoising(srcImage, denoised, 10);

    Mat image = denoised;

    Ptr<CLAHE> clahe = createCLAHE();
    clahe->setClipLimit(30.0);
    clahe->setTilesGridSize(Size(8, 8));
    Mat imgray_ad;
    clahe->apply(image, imgray_ad);
    Mat imgray;
    cv::equalizeHist(image, imgray);
    imshow("imgray_ad", imgray_ad);
    imshow("imgray", imgray);

    Mat thresh;
    threshold(imgray_ad, thresh, 150, 255, THRESH_BINARY | THRESH_OTSU);
    imshow("thresh", thresh);

    Mat result;
    Mat kernel = Mat::ones(8, 8, CV_8UC1);

    erode(thresh, result, kernel);
    imshow("result", result);

    waitKey();
    return 0;
}

Origin:
https://stackoverflow.com/a/47531223/1645289


战国战争史:秦国收复河西之战
河西之战是中国战国时代,魏国与秦国为争夺关中河西(今山西、陕西两省间黄河南段以西地区)地区发生的大规模战争,前后反复交战数次,秦经过商鞅变法国力大增,恰逢魏国精锐丧失殆尽国力大损,最终秦收复河西。