OPENCV+TENSORFLOW篇3_仿射变换与旋转

仿射变换就是平面到平面的映射,由于三点确定平面,因此,原平面到新平面找到对应三点即可确定映射关系(所谓关系就是变化矩阵)

import cv2
import numpy as np
img = cv2.imread('image0.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([[50,50],[300,height-200],[width-300,100]])

matAffine =cv2.getAffineTransform(matSrc,matDst)
dst = cv2.warpAffine(img,matAffine,(width,height))
cv2.imshow('dst',dst)
cv2.waitKey()

旋转就更简单了,都是获得变换矩阵

import cv2
import numpy as np

img = cv2.imread('image0.JPG',1)
cv2.imshow('src',img)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

matRotate = cv2.getRotationMatrix2D((height*0.5,width*0.5),45,0.5)#center angle ratio

dst = cv2.warpAffine(img,matRotate,(width,height))
cv2.imshow('dst',dst)
cv2.waitKey(0)

借楼放一个边缘检测
灰度、高斯滤波、canny API

import cv2
import numpy as np
import random

img = cv2.imread('image0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
imgG = cv2.GaussianBlur(gray,(3,3),0)
dst = cv2.Canny(img,50,50)
cv2.imshow('dst',dst)
cv2.waitKey(0)

sobel 计算

import cv2
import numpy as np
import random
import math

img = cv2.imread('image0.jpg',1)
imgInfo = img.shape
height = imgInfo[0]
width = imgInfo[1]

gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
dst = np.zeros((height,width,1),np.uint8)

for i in range(0,height-2):
    for j in range(0,width-2):
        gy = gray[i,j]*1 + gray[i,j+1]*2 + gray[i,j+2] - gray[i+2,j] - gray[i+2,j+1]*2 - gray[i+2,j+2]
        gx = gray[i,j]*1 + gray[i+1,j]*2 + gray[i+2,j] - gray[i,j+2] - gray[i+1,j+2]*2 - gray[i+2,j+2]
        grad = math.sqrt(gx*gx + gy*gy)
        if grad > 50:
            dst[i,j] = 255
        else:
            dst[i,j] = 0
            
cv2.imshow('dst',dst)
cv2.waitKey(0)

你可能感兴趣的:(ML,Python)