前言
本文提供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;
}
结果如下所示: