1. 程式人生 > >使用Python手動實現影象平移、旋轉、水平映象等

使用Python手動實現影象平移、旋轉、水平映象等

原部落格

一、影象平移
這裡寫圖片描述
二、影象水平映象
這裡寫圖片描述
三、影象垂直映象
這裡寫圖片描述
四、影象縮放
這裡寫圖片描述
這裡寫圖片描述
五、影象旋轉
這裡寫圖片描述

Python程式碼實現:

import cv2
import math
import numpy as np

class Img:
    def __init__(self,image,rows,cols,center=[0,0]):
        self.src=image #原始影象
        self.rows=rows #原始影象的行
        self.cols=cols #原始影象的列
self.center=center #旋轉中心,預設是[0,0] def Move(self,delta_x,delta_y): #平移 #delta_x>0左移,delta_x<0右移 #delta_y>0上移,delta_y<0下移 self.transform=np.array([[1,0,delta_x],[0,1,delta_y],[0,0,1]]) def Zoom(self,factor): #縮放 #factor>1表示縮小;factor<1表示放大
self.transform=np.array([[factor,0,0],[0,factor,0],[0,0,1]]) def Horizontal(self): #水平映象 self.transform=np.array([[1,0,0],[0,-1,self.cols-1],[0,0,1]]) def Vertically(self): #垂直映象 self.transform=np.array([[-1,0,self.rows-1],[0,1,0],[0,0,1]]) def Rotate
(self,beta):
#旋轉 #beta>0表示逆時針旋轉;beta<0表示順時針旋轉 self.transform=np.array([[math.cos(beta),-math.sin(beta),0], [math.sin(beta), math.cos(beta),0], [ 0, 0, 1]]) def Process(self): self.dst=np.zeros((self.rows,self.cols),dtype=np.uint8) for i in range(self.rows): for j in range(self.cols): src_pos=np.array([i-self.center[0],j-self.center[1],1]) [x,y,z]=np.dot(self.transform,src_pos) x=int(x)+self.center[0] y=int(y)+self.center[1] if x>=self.rows or y>=self.cols or x<0 or y<0: self.dst[i][j]=255 else: self.dst[i][j]=self.src[x][y] if __name__=='__main__': src=cv2.imread('.\jay.bmp',0) rows = src.shape[0] cols = src.shape[1] cv2.imshow('src', src) img=Img(src,rows,cols,[248,231]) img.Vertically() #映象 img.Process() ''' img.Rotate(-math.radians(180)) #旋轉 img.Process() img.Move(-50,-50) #平移 img.Process() img.Zoom(0.5) #縮放 img.Process() ''' cv2.imshow('dst', img.dst) cv2.waitKey(0)