1. 线性变换
代码:
import cv2
import random
import imutils
import numpy as np
# 彩色图像每个像素值是[x,y,z], 灰度图像每个像素值便是一个np.uint8
image = cv2.imread('E:/1.PNG')
gray_img = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) #将彩色图像变为灰度图像(RGB彩色变灰色)
# 图像大小调整
ori_h, ori_w = image.shape[:2] #获得原图像长宽
height, width = gray_img.shape[:2] #获得灰度图像长宽
image = cv2.resize(image, (int(ori_w / ori_h * 400), 400), interpolation=cv2.INTER_CUBIC) #对图像大小变换且做三次插值
gray_img = cv2.resize(gray_img, (int(width / height * 400), 400), interpolation=cv2.INTER_CUBIC) #对图像大小变换且做三次插值
# a1: 增强图像的对比度,图像看起来更加清晰
a, b = 1.5, 20
new_img2 = np.ones((gray_img.shape[0], gray_img.shape[1]), dtype=np.uint8)
for i in range(new_img2.shape[0]):
for j in range(new_img2.shape[1]):
if gray_img[i][j] * a + b > 255:
new_img2[i][j] = 255
else:
new_img2[i][j] = gray_img[i][j] * a + b
# a 255:
new_img4[i][j] = 255
elif pix < 0:
new_img4[i][j] = 0
else:
new_img4[i][j] = pix
# a=-1, b=255, 图像翻转
new_img5 = 255 - gray_img
cv2.imshow('origin', imutils.resize(image, 800))
cv2.imshow('gray', imutils.resize(gray_img, 800))
cv2.imshow('a1 and b>=0', imutils.resize(new_img2, 800))
cv2.imshow('a=0', imutils.resize(new_img3, 800))
cv2.imshow('a=1 and b> |