【课程作业】图像灰度变换、几何变换及图像运算

彩色图转换为灰度图

运行代码

import cv2 # 导入opencv包
import numpy as np

img = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
# print(img.dtype) uint8
# print(type(img.shape)) 为元组类型 (512, 510, 3)
h, w = img.shape[0:2] #tuplename[start : end : step] 前闭后开 取前两列 获取水平像素和竖直像素个数
gray = np.zeros((h, w), dtype=img.dtype)
# print(gray[400])
for i in range(h):
    for j in range(w):
        # 把gray每一个像素点值根据原图rgb的值赋权转换为灰度
        gray[i, j] = (0.3*int(img[i, j, 0]) + 0.59*int(img[i, j, 1]) + 0.11*int(img[i, j, 2]))
        
cv2.imshow("graypic",gray)# 每一个像素按gray二维数组里边的颜色进行填充,灰色
cv2.imshow("Result",img)
cv2.waitKey(0)

运行效果

在这里插入图片描述

cv2.cvtColor 函数实现彩色图像转化为灰度图像

运行代码

import cv2 # 导入opencv包
import numpy as np

img = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
print(img.shape)
dst = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
cv2.imshow('ok', dst)
cv2.waitKey(0)

运行效果

在这里插入图片描述
注意:COLOR_RGB2GRAY 代表 ‘rgb to gray’

灰度拉伸 灰度压缩

运行代码

import numpy as np
import cv2
from matplotlib import pyplot as plt
# 定义线性灰度变化函数
# k>1 时 实现灰度数值的拉伸
# 0<k<1 时 实现灰度数值的压缩
# k=-1 b=255 实现灰度反转
#灰度表函数如下↓
def linear_trans(img, k, b=0):
    # 计算灰度线性变化的映射表
    trans_list = [(np.float32(x)*k+b) for x in range(256)]
    # 将列表转换为 np.array
    trans_table =np.array(trans_list)
    # 将超过[0,255]灰度范围的数值进行调整,并指定数据类型为 uint8
    trans_table[trans_table>255] = 255
    trans_table[trans_table<0] = 0
    trans_table = np.round(trans_table).astype(np.uint8)
    # 使用 OpenCV 的 look up table 函数修改图像的灰度值
    return cv2.LUT(img, trans_table) #返回查表后的图像

im = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
cv2.imshow('org', im)
# 反转
im_inversion = linear_trans(im, -1, 255)
cv2.imshow('inversion', im_inversion)
# 灰度拉伸
im_stretch = linear_trans(im, 1.2)
cv2.imshow('graystretch', im_stretch)
# 灰度压缩
im_compress = linear_trans(im, 0.8)
cv2.imshow('graycompress', im_compress)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行结果

在这里插入图片描述

图像平移

运行代码

import numpy as np
import cv2
# 定义平移 translate 函数

def translate(img, x, y):
    # 获取图像尺寸
    (h, w) = img.shape[:2]
    # 定义平移矩阵
    M = np.float32([[1, 0, x], [0, 1, y]])
    # 使用 OpenCV 仿射变换函数实现平移操作
    shifted = cv2.warpAffine(img, M, (w, h))
    # 返回转换后的图像
    return shifted
    # 加载图像并显示

im = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
cv2.imshow("Orig", im)
# 对原图做平移操作
#右、下移为正,左、上移为负

# 下移 50 像素
shifted = translate(im, 0, 200)
cv2.imshow("Shift1", shifted)
# 左移 100 像素
shifted = translate(im, -100, 0)
cv2.imshow("Shift2", shifted)
# 右移 50,下移 100 像素
shifted = translate(im, 50, 100)
cv2.imshow("Shift3", shifted)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行效果

在这里插入图片描述

旋转变换

运行代码

import numpy as np
import cv2
# 定义旋转 rotate 函数
def rotate(img, angle, center=None, scale=1.0):
    # 获取图像尺寸
    (h, w) = img.shape[:2]
    # 旋转中心的缺失值为图像中心
    if center is None:
        center = (w / 2, h / 2)
    # 调用计算旋转矩阵函数
    M = cv2.getRotationMatrix2D(center, angle, scale)
    # 使用 OpenCV 仿射变换函数实现旋转操作
    rotated = cv2.warpAffine(img, M, (w, h))
    # 返回旋转后的图像
    return rotated

im = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
cv2.imshow("Orig", im)
# 对原图做旋转操作
# 逆时针 45 度
rotated = rotate(im, 45)
cv2.imshow("Rotate1", rotated)
# 顺时针 20 度
rotated = rotate(im, -20)
cv2.imshow("Rotate2", rotated)
# 逆时针 90 度
rotated = rotate(im, 90)
cv2.imshow("Rotate3", rotated)
cv2.waitKey(0)
cv2.destroyAllWindows()

运行结果

在这里插入图片描述

镜像翻转

运行代码

import numpy as np
import cv2

im = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")

# 进行垂直镜像
im_flip0 = cv2.flip(im, 0)

# 进行水平镜像
im_flip1 = cv2.flip(im, 1)
cv2.imshow("flip1", im_flip0)
cv2.imshow("flip2", im_flip1)

cv2.waitKey(0)
cv2.destroyAllWindows()

运行效果
在这里插入图片描述

缩放

运行代码

import numpy as np
import cv2
im = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
cv2.imshow("orig", im)

# 获取图像尺寸
(h, w) = im.shape[:2]
# 缩放的目标尺寸
dst_size = (200,300)
# 最邻近插值
# 进行缩放
resized = cv2.resize(im, dst_size, interpolation = cv2.INTER_NEAREST)
cv2.imshow("scale1", resized)


# 缩放的目标尺寸
dst_size = (800,600)
# 双线性插值
method = cv2.INTER_LINEAR
# 进行缩放
resized = cv2.resize(im, dst_size, interpolation = method)
cv2.imshow("scale2", resized)

cv2.waitKey(0)
cv2.destroyAllWindows()

运行效果

在这里插入图片描述

练习:仿射变换

运行代码

import cv2 
import numpy as np 

img = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")

h, w = img.shape[0:2]

# 在原图像和目标图像上各选择三个点 
mat_src = np.float32([[0, 0],[0, h],[w, 0]]) 
mat_dst = np.float32([[0, 0],[100, h],[w, 0]]) 

# 得到变换矩阵 
mat_trans = cv2.getAffineTransform(mat_src, mat_dst) 
# 进行仿射变换 
dst = cv2.warpAffine(img, mat_trans, (w,h)) 

# 显示 
imgs = np.hstack([img,dst]) 
# cv2.namedWindow('imgs', cv2.WINDOW_NORMAL) 
cv2.imshow("imgs",dst) 
cv2.waitKey(0)

运行结果

在这里插入图片描述

练习:不同分辨率图像融合

运行代码

import cv2
import numpy as np

lena = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/lena.png")
pic2 = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/fusion1.png")

rows, cols = pic2.shape[:2] #获取sky的高度、宽度
dst = cv2.resize(lena,(cols,rows),interpolation=cv2.INTER_CUBIC) #放大图像
add_img = cv2.addWeighted(dst,0.6,pic2,0.4,0) #图像融合
cv2.imshow('add_img', add_img)
cv2.imshow('ori1', pic2)
cv2.imshow('ori2', lena)
cv2.waitKey(0)

运行效果

在这里插入图片描述

练习:gaamma 变换

运行代码

import cv2
import numpy as np

img = cv2.imread ("D:/Project/PythonProject/GraphicAnalysis/class2/fusion2.png")

gammaList = [0.125, 0.25, 0.5, 1.0, 2.0, 4.0]  # gamma 值
normImg = lambda x: 255. * (x-x.min()) / (x.max()-x.min()+1e-6)  # 归一化为 [0,255]
cv2.imshow('original', img)
for k in range(len(gammaList)):
    imgGamma = np.power(img, gammaList[k])
    imgGamma = np.uint8(normImg(imgGamma))

    cv2.imshow('r'+str(k), imgGamma)
cv2.waitKey(0)

运行效果

在这里插入图片描述

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

a9c93f2300

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值