Opencv4圖像分割和識別第三課(實戰2)濾鏡特效

前言

本文提供Opencv4圖像分割和識別課程(https://edu.csdn.net/course/detail/24864)第三課(實戰2)的兩個課後作業代碼。

直方圖均衡化

一種間接(使直方圖均勻分佈)增強圖像對比度的方法。原理在課程裏面有詳細說明,這裏不在贅述。其python版實現代碼如下,源圖片在課件裏提供。

5.	import numpy as np
import cv2
from matplotlib import pyplot as plt

def get_histogram(img):
    (height, width) = img.shape
    hist = np.zeros((256), np.uint32)
    for i in range(height):
        for j in range(width):
            hist[img[i, j]] = hist[img[i, j]] + 1
    return hist

def equalize_histogram():
    img = cv2.imread('xxx/hist_orig.jpg', cv2.IMREAD_GRAYSCALE)
    (height, width) = img.shape

    hist_img = np.zeros((height, width), np.uint8)
    hist_gram = get_histogram(img)

    num_pixels = height * width
    lut = np.zeros((256), np.uint8)
    lut[0] = 1.0 * hist_gram[0] / num_pixels * 255

    sum = hist_gram[0]
    for i in range(1, 256):
        sum = sum + hist_gram[i]
        lut[i] = 1.0 * sum / num_pixels * 255

    for i in range(height):
        for j in range(width):
            hist_img[i, j] = lut[img[i, j]]

    plt.hist(img.ravel(), 256, [0, 256])
    plt.hist(hist_img.ravel(), 256, [0, 256])
    plt.show()
    cv2.imshow('original', img)
    cv2.imshow('hist', hist_img)
    cv2.waitKey()

結果如下:

 

源圖像上的目標分割 

本課程實戰一(https://blog.csdn.net/avideointerfaces/article/details/91127315其實只實現了二值圖上把目標分割出來,本作業再進一步將源圖像上的目標給找到,並分割出來。 其關鍵函數會在課件裏面解釋,這裏只提供實現代碼:

int bear_segment2(const char *file_name, Mat &result_img)
{
	Mat img = imread(file_name);
	if (img.empty())
	{
		printf("reading image fails \n");
		return -1;
	}

	Mat img_gray;
	cvtColor(img, img_gray, COLOR_BGR2GRAY);

	Mat img_bin;
	threshold(img_gray, img_bin, 120, 255, THRESH_BINARY_INV);

	Mat segment_bin(Size(img.cols, img.rows), CV_8UC1, Scalar(0));

	vector<vector<Point>> contours;
	//findContours(img_bin, contours, CV_RETR_EXTERNAL, CV_CHAIN_APPROX_NONE); //opencv3.x
	findContours(img_bin, contours, RETR_EXTERNAL, CHAIN_APPROX_NONE);
	int i, size;
	size = contours.size();
	for (i = 1; i < size; i++)
	{
		if (contourArea(contours[i]) > 20000)
		{
			drawContours(segment_bin, contours, i, Scalar(255), FILLED);
		}
	}

	result_img = Mat(Size(img.cols, img.rows), CV_8UC3, Scalar(255, 255, 255));
	//Mat bear_img;
	img.copyTo(result_img, segment_bin);
	return 0;
}

結果如下所示:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章