python使用opencv实现图像处理亮度调节+旋转+归一化
·
- opencv_图像归一化
# coding=utf-8
import os
import math
import numpy as np
import cv2
# 角度调整
def rotate(img, angle):
# img = cv2.imread(img_path)
# Get image dimensions
height, width = img.shape[:2]
# print(img.shape)
# Calculate the rotation matrix [2X3]
rotation_matrix = cv2.getRotationMatrix2D((width/2, height/2), angle, 1)
# 原坐标系下的宽高
pts = np.array([[0, 0],
[0, height-1],
[width-1, 0],
[width-1, height-1]], dtype=np.float32)
# print(pts.shape) (4, 2)
# print(pts.reshape(-1, 1, 2).shape) (4,1,2)
# 进行坐标变换
dest_pts = cv2.transform(pts.reshape(-1, 1, 2), rotation_matrix)
# print(dest_pts.shape)
dest_pts = dest_pts.reshape(pts.shape)
# 返回包括输入信息的最小外接正矩形
x, y, new_width, new_height = cv2.boundingRect(dest_pts)
# print(x, y, new_width, new_height)
rotation_matrix[0, 2] -= x
rotation_matrix[1, 2] -= y
# print(rotation_matrix)
# 计算旋转之后目标坐标系的宽高
# new_width, new_height = np.max(dest_pts, axis=0) - np.min(dest_pts, axis=0)
# 返回覆盖输入信息的最小斜矩形
rect = cv2.minAreaRect(dest_pts)
# (center, size, angle) = rect
# tx = (new_width - width)/2
# ty = (new_height - height)/2
# rotation_matrix[0, 2] += tx
# rotation_matrix[1, 2] += ty
# Perform the rotation using warpAffine function
rotated_img = cv2.warpAffine(img, rotation_matrix, (int(new_width), int(new_height)))
# cv2.imwrite(dest_path, rotated_img)
return rotated_img
# 亮度调整
# value {0, 2}
def brightness(img, alpha=0.5):
hsv_img = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
img = hsv_img * 1.0
img_out = img
# 线性调整
img_out[:, :, 2] = hsv_img[:, :, 2] * alpha
# HSV亮度上下限处理(小于0取0,大于1取1)
img_out = img_out / 255.0
mask_1 = img_out < 0
mask_2 = img_out > 1
img_out = img_out * (1 - mask_1)
img_out = img_out * (1 - mask_2) + mask_2
img_out = img_out * 255.0
# HSV转RGB
img_out = np.round(img_out).astype(np.uint8)
img_out = cv2.cvtColor(img_out, cv2.COLOR_HSV2BGR)
return img_out
# 缩放
def resize_image(img: np.array, scale):
"""缩放"""
# 获取图片的宽度和高度
height, width= img.shape[:2]
# 定义缩放比例scale
# 计算缩放后的尺寸
new_width = int(width * scale)
new_height = int(height * scale)
# 进行缩放
img_resized = cv2.resize(img, dsize=(new_width, new_height))
return img_resized
#扭曲变换调整
def warpPerspective(img, x_scale, y_scale):
h, w = img.shape[:2]
dest_w = int(x_scale * w)
dest_h = int(y_scale * h)
pts1 = np.float32([[0, 0], [w - 1, 0], [w - 1, h - 1], [0, h - 1]])
pts2 = np.float32([[0, 0], [dest_w - 1, 0], [dest_w - 1, dest_h - 1], [0, dest_h - 1]])
matrix = cv2.getPerspectiveTransform(pts1, pts2)
dest = cv2.warpPerspective(img, matrix, (dest_w, dest_h))
return dest
def psnr(img1: np.asarray, img2: np.asarray):
src = np.float32(img1)
dest = np.float32(img2)
mse = np.mean((src - dest) ** 2)
max_value = np.max(src)
if mse == 0:
return 100
return 20 * math.log10(max_value / math.sqrt(mse))
def operate_file_api(infile, outfile, flag=0):
source = cv2.imread(infile)
if source is None:
print("input path is not unvalid.")
return
if flag == 0:
dest = warpPerspective(source, 1.0, 2.0)
elif flag == 1:
dest = resize_image(source, 0.5)
elif flag == 2:
dest = brightness(source, 0.5)
else:
return
cv2.imwrite(outfile, dest)
return 0
if __name__ == "__main__":
infile = "./1/1.jpg"
outfile = "./1-tmp.jpg"
operate_file_api(infile, outfile, 2)
#include <cv.h>
#include <highgui.h>
void zscoreNormalize(const cv::Mat& src, cv::Mat& dst)
{
// compute mu and mu squared
cv::Mat mu(src.size(), src.type());
cv::GaussianBlur(src, mu, cv::Size(7, 7), 1.166);
cv::Mat mu_sq;
cv::multiply(mu, mu, mu_sq);
// compute sigma (local sigma)
cv::Mat sigma(src.size(), src.type());
cv::multiply(src, src, sigma);
cv::GaussianBlur(sigma, sigma, cv::Size(7, 7), 1.166);
cv::subtract(sigma, mu_sq, sigma);
cv::pow(sigma, double(0.5), sigma);
cv::add(sigma, cv::Scalar(1.0 / 255), sigma);
cv::subtract(src, mu, dst);
cv::divide(dst, sigma, dst);
}
void zscoreNormalize_v2(const cv::Mat& src, cv::Mat& dst)
{
cv::Mat mu(src.size(), src.type());
cv::GaussianBlur(src, mu, cv::Size(7, 7), 1.166);
cv::subtract(src, mu, mu);
cv::Mat sigma(src.size(), src.type());
cv::multiply(mu, mu, sigma);
cv::GaussianBlur(sigma, sigma, cv::Size(7, 7), 1.166);
cv::pow(sigma, 0.5, sigma);
cv::add(sigma, cv::Scalar(1.0 / 255), sigma);
cv::divide(mu, sigma, dst);
}
template<typename Func>
double bench_(const Func& func, unsigned int iterNum = 1)
{
auto t1 = cv::getTickCount();
while (iterNum--) func();
auto t2 = cv::getTickCount();
return 1000.0 * (t2 - t1) / cv::getTickFrequency();
}
void show(const std::string& winname, const cv::Mat& src)
{
cv::Mat normalized;
cv::normalize(src, normalized, 255, 0, CV_MINMAX, CV_8U);
cv::bitwise_not(normalized, normalized);
cv::imshow(winname, normalized);
}
int main()
{
cv::Mat src = cv::imread("lena.jpg", 0);
cv::Mat src64f;
src.convertTo(src64f, CV_64F, 1.0 / 255);
cv::Mat dst64f(src.size(), src.type());
int iterNum = 10;
printf("zscoreNormalize %f ms\n", bench_([&](){zscoreNormalize(src64f, dst64f); }, iterNum));
show("zscoreNormalize", dst64f);
printf("zscoreNormalize_v2 %f ms\n", bench_([&](){zscoreNormalize_v2(src64f, dst64f); }, iterNum));
show("zscoreNormalize_v2", dst64f);
cv::waitKey();
return 0;
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)