Python+OpenCV 实现图片无损旋转90°且无黑边
作者:FistQ 时间:2021-11-09 17:04:12
0. 引言
有如上一张图片,在以往的图像旋转处理中,往往得到如图所示的图片。
然而,在进行一些其他图像处理或者图像展示时,黑边带来了一些不便。本文解决图片旋转后出现黑边的问题,实现了图片尺寸不变的旋转(以上提到的黑边是图片的一部分)。
1. 方法流程
(1)旋转图片,得到有黑边的旋转图片。
(2)找出图片区域(不含黑边)的位置。
(3)创建一个空图片(其实是矩阵)。
(4)将图片区域搬到此空图片。
2. 程序
#!/usr/bin/python
# -*- coding: UTF-8 -*-
"""
This program is debugged by Harden Qiu.
You can send a e-mail to hardenqiu@foxmail.com for more details.
"""
import numpy as np
import cv2
def main():
img = cv2.imread('.\\imgs\\img10.jpg')
height, width = img.shape[:2]
matRotate = cv2.getRotationMatrix2D((height * 0.5, width * 0.5), -90, 1)
dst = cv2.warpAffine(img, matRotate, (width, height*2))
rows, cols = dst.shape[:2]
for col in range(0, cols):
if dst[:, col].any():
left = col
break
for col in range(cols-1, 0, -1):
if dst[:, col].any():
right = col
break
for row in range(0, rows):
if dst[row,:].any():
up = row
break
for row in range(rows-1,0,-1):
if dst[row,:].any():
down = row
break
res_widths = abs(right - left)
res_heights = abs(down - up)
res = np.zeros([res_heights ,res_widths, 3], np.uint8)
for res_width in range(res_widths):
for res_height in range(res_heights):
res[res_height, res_width] = dst[up+res_height, left+res_width]
cv2.imshow('res',res)
cv2.imshow('img',img)
cv2.imshow('dst', dst)
cv2.waitKey(0)
if __name__ =='__main__':
main()
说明:img表示原图,dst表示旋转后图片,res表示最终处理获取的图片。
运行程序,得到如图所示的图片,解决了遇到的问题。
3. 总结
本图像处理方法用到了以下几个重要函数:
cv2.getRotationMatrix2D
cv2.warpAffine
编程过程中,要理清楚图片各个像素点的横纵变化及其变化大小。在进行像素传递时,要注意对应关系。
来源:https://blog.csdn.net/qq_23149979/article/details/90176543
标签:Python,OpenCV,图片旋转
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
MSSQL优化之探索MSSQL执行计划(转)
2011-11-03 17:16:21
Python实现常见的回文字符串算法
2022-07-10 10:32:29
asp get和post数据接收过滤
2011-04-06 10:52:00
python yield关键词案例测试
2021-02-07 03:14:07
Python Flask-Login模块使用案例详解
2021-10-14 21:01:17
![](https://img.aspxhome.com/file/2023/0/90590_0s.png)
Python叠加两幅栅格图像的实现方法
2023-07-25 17:14:06
![](https://img.aspxhome.com/file/2023/5/61485_0s.jpg)
python实现根据ip地址反向查找主机名称的方法
2023-12-21 01:58:06
pytorch交叉熵损失函数的weight参数的使用
2021-02-27 15:52:31
![](https://img.aspxhome.com/file/2023/3/101703_0s.jpg)
python opencv进行图像拼接
2022-09-10 16:13:01
![](https://img.aspxhome.com/file/2023/6/78716_0s.jpg)
教你快速掌握更改表中列顺序的好方法
2008-11-27 17:14:00
Python列表排序 list.sort方法和内置函数sorted用法
2022-01-18 01:01:47
关于Ajax在浏览器中产生前进后退的实现方法
2010-01-29 13:01:00
屏蔽Flash 右键菜单的方法
2008-05-24 07:21:00
随滚动条移动的DIV层js代码
2007-10-10 12:51:00
Python使用future处理并发问题方案详解
2022-12-10 18:16:53
Python实现线程池代码分享
2021-09-24 18:13:43
3个常用的JS时间代码
2009-03-22 15:29:00
AJAX实战实现级联选择
2009-08-21 12:27:00
python中opencv 直方图处理
2021-12-24 09:45:17
![](https://img.aspxhome.com/file/2023/5/90595_0s.webp)
JS 显示当前日期+星期(静态)
2007-09-11 13:29:00