Python+OpenCV+图片旋转并用原底色填充新四角的例子
作者:默盒 时间:2022-09-07 14:11:23
我就废话不多说了,直接上代码吧!
import cv2
from math import fabs, sin, cos, radians
import numpy as np
from scipy.stats import mode
def get_img_rot_broa(img, degree=45, filled_color=-1):
"""
Desciption:
Get img rotated a certain degree,
and use some color to fill 4 corners of the new img.
"""
# 获取旋转后4角的填充色
if filled_color == -1:
filled_color = mode([img[0, 0], img[0, -1],
img[-1, 0], img[-1, -1]]).mode[0]
if np.array(filled_color).shape[0] == 2:
if isinstance(filled_color, int):
filled_color = (filled_color, filled_color, filled_color)
else:
filled_color = tuple([int(i) for i in filled_color])
height, width = img.shape[:2]
# 旋转后的尺寸
height_new = int(width * fabs(sin(radians(degree))) +
height * fabs(cos(radians(degree))))
width_new = int(height * fabs(sin(radians(degree))) +
width * fabs(cos(radians(degree))))
mat_rotation = cv2.getRotationMatrix2D((width / 2, height / 2), degree, 1)
mat_rotation[0, 2] += (width_new - width) / 2
mat_rotation[1, 2] += (height_new - height) / 2
# Pay attention to the type of elements of filler_color, which should be
# the int in pure python, instead of those in numpy.
img_rotated = cv2.warpAffine(img, mat_rotation, (width_new, height_new),
borderValue=filled_color)
# 填充四个角
mask = np.zeros((height_new + 2, width_new + 2), np.uint8)
mask[:] = 0
seed_points = [(0, 0), (0, height_new - 1), (width_new - 1, 0),
(width_new - 1, height_new - 1)]
for i in seed_points:
cv2.floodFill(img_rotated, mask, i, filled_color)
return img_rotated
来源:https://www.cnblogs.com/ZhengPeng7/p/7390119.html
标签:Python,OpenCV,图片旋转
0
投稿
猜你喜欢
python实现ID3决策树算法
2021-03-15 14:30:13
关于MySQL索引的几点值得注意的事项
2024-01-27 17:51:32
Python requests用法和django后台处理详解
2023-06-12 02:05:42
JavaScript数组的5种迭代方法
2024-04-22 22:17:42
python3爬取淘宝信息代码分析
2021-05-03 04:59:11
Django重置migrations文件的方法步骤
2023-06-17 07:01:38
python ftp 按目录结构上传下载的实现代码
2021-01-28 00:38:33
在自动化中用python实现键盘操作的方法详解
2021-02-04 00:23:48
微信小程序(十二)text组件详细介绍
2024-04-19 09:43:53
asp使用jmail4.3的模块
2010-03-17 20:58:00
python基于paramiko库远程执行 SSH 命令,实现 sftp 下载文件
2022-11-09 23:31:31
简单了解Python多态与属性运行原理
2021-03-13 21:29:42
Django更新models数据库结构步骤
2024-01-16 09:05:25
Python读写二进制文件的实现
2023-07-20 14:48:52
mysql 8.0.27 安装配置方法图文教程(Windows64位)
2024-01-19 07:37:59
用python爬取分析淘宝商品信息详解技术篇
2022-09-12 23:40:54
python自动化测试selenium屏幕截图示例
2022-07-13 16:55:14
python神经网络tensorflow利用训练好的模型进行预测
2022-09-27 17:33:17
python3利用Socket实现通信的方法示例
2022-04-10 03:09:04
实例讲解Oracle到SQL Server主键迁移
2009-03-25 13:30:00