【OpenCV】图片裁切 移位 翻转 缩放 仿射变换 图片旋转

 从慕课网《opencv 》相关课程总结而来

#图片裁切
import cv2
img = cv2.imread('G:/1.jpg',1)
imgInfo = img.shape
dst = img[100:200,100:300]
cv2.imshow('image',dst)
cv2.waitKey(0)
#图片移位
#1  API的使用
#2  算法原理
#3  源代码
import cv2
import numpy as np
img = cv2.imread('G:/1.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
####
matShift = np.float32([[1,0,100],[0,1,200]])#2x3
dst = cv2.warpAffine(img,matShift,(height,width))
cv2.imshow('dst',dst)
cv2.waitKey(0)


#API的原理
#[1,0,100],[0,1,200] 2x2 2x1
#[[1,0],[0,1]]  2x2  A
#[[100],[200]] 2x1   B
#xy c
#AxC+B = [[1*x +0*y],[0*x+1*y]]+[[100],[200]]
# =  [[x+100],[y+200]]

#(10,20) -> (110,220)


#通过源码实现位移
import cv2
import numpy as np
img = cv2.imread('G:/1.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
#定义一个空矩阵 与原始图片等大
dst = np.zeros(img.shape,np.uint8)
height = imgInfo[0]
width = imgInfo[1]
for i in range(0,height):
    for j in range(0,width-100):
        dst[i,j+100] = img[i,j]
cv2.imshow('dst',dst)
cv2.waitKey(0)
        
#图片翻转
#1 创建一个“画板”,需要足够大
# 2  将一副图像分别从前向后,从后向前绘制
#3 绘制中心分割线
import cv2
import numpy as np
img = cv2.imread('G:/02.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
deep = imgInfo[2]
newImgInfo = (height*2,width,deep)
dst = np.zeros(newImgInfo,np.uint8)
for i in range(0,height):
    for j in range(0,width):
        dst[i,j] = img[i,j]
        # x  y = 2*h - y -1
        dst[height*2 - i-1,j] = img[i,j]
for i in range(0,width):
    dst[height,i] = (0,0,225)
cv2.imshow('dst',dst)
cv2.waitKey(0)
#图片缩放
#[[A1 A2 B],[A3 A4 B2]]
#[[A1 A2],[A3 A4]]  [[B1]  ,[B2]]
#newX = A1*x+A2*y+B1
#newY = A3*x +A4*y +B2
#x->x*0.5  y->y*0.5
#newX = 0.5*x
import cv2
import numpy as np
img = cv2.imread('G:/02.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
matScale = np.float32([[0.5,0,0],[0,0.5,0]])
dst = cv2.warpAffine(img,matScale,(int(width*0.5),int(height*0.5)))
cv2.imshow('dst',dst)
cv2.waitKey(0)
#图片的仿射变换
# 位移 旋转  缩放
import cv2
import numpy as np
img = cv2.imread('G:/02.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#仿射变换的原理就是将原图像的左上角,左下角,右上角映射到新的三个点上
matSrc = np.float32([[0,0],[0,height-1],[width-1,0]])
matDst = np.float32([[150,50],[150,height-100],[width-100,100]])
#组合
matAffine = cv2.getAffineTransform(matSrc,matDst)
dst = cv2.warpAffine(img,matAffine,(width,height))
cv2.imshow('dst',dst)
cv2.waitKey(0)
#图片旋转
import cv2
import numpy as np
img = cv2.imread('G:/02.jpg',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]
#定义一个mat的旋转矩阵
#2 * 3
matRotate = cv2.getRotationMatrix2D((height*0.5,width*0.5),45,0.5) # 旋转中心  旋转角度 缩放大小,缩放系数
dst = cv2.warpAffine(img,matRotate,(height,width))
cv2.imshow('dst',dst)
cv2.waitKey(0)

猜你喜欢

转载自blog.csdn.net/weixin_40874586/article/details/81608958