python opencv图片旋转如何匹配_图像旋转任意角度不缺失,缺失背景指定颜色填充(python+opencv)图文教程和完整项目代码...

效果展示

代码

# -*- coding: utf-8 -*-

import cv2

from math import *

import numpy as np

# 旋转angle角度,缺失背景白色(255, 255, 255)填充

def rotate_bound_white_bg(image, angle):

# grab the dimensions of the image and then determine the

# center

(h, w) = image.shape[:2]

(cX, cY) = (w // 2, h // 2)

# grab the rotation matrix (applying the negative of the

# angle to rotate clockwise), then grab the sine and cosine

# (i.e., the rotation components of the matrix)

# -angle位置参数为角度参数负值表示顺时针旋转; 1.0位置参数scale是调整尺寸比例(图像缩放参数),建议0.75

M = cv2.getRotationMatrix2D((cX, cY), -angle, 1.0)

cos = np.abs(M[0, 0])

sin = np.abs(M[0, 1])

# compute the new bounding dimensions of the image

nW = int((h * sin) + (w * cos))

nH = int((h * cos) + (w * sin))

# adjust the rotation matrix to take into account translation

M[0, 2] += (nW / 2) - cX

M[1, 2] += (nH / 2) - cY

# perform the actual rotation and return the image

# borderValue 缺失背景填充色彩,此处为白色,可自定义

return cv2.warpAffine(image, M, (nW, nH),borderValue=(255,255,255))

# borderValue 缺省,默认是黑色(0, 0 , 0)

# return cv2.warpAffine(image, M, (nW, nH))

img = cv2.imread("dog.png")

imgRotation = rotate_bound_white_bg(img, 45)

cv2.imshow("img",img)

cv2.imshow("imgRotation",imgRotation)

cv2.waitKey(0)

returncv2.warpAffine(image, M, (nW, nH),borderValue=(255,255,255))# borderValue 缺失背景色彩,此处为白色,可自定义

return cv2.warpAffine(image, M, (nW, nH)) # borderValue 缺省,默认是黑色(0, 0 , 0),效果如下

素材

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值