Python+OpenCV 实现图片无损旋转90°且无黑边

yipeiwu_com6年前Python基础

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

编程过程中,要理清楚图片各个像素点的横纵变化及其变化大小。在进行像素传递时,要注意对应关系。

以上这篇Python+OpenCV 实现图片无损旋转90°且无黑边就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python操作Word批量生成文章的方法

Python操作Word批量生成文章的方法

下面通过COM让Python与Word建立连接实现Python操作Word批量生成文章,具体介绍请看下文: 需要做一些会议记录。总共有多少呢?五个地点x7个月份x每月4篇=140篇。虽然...

使用TensorFlow实现二分类的方法示例

使用TensorFlow实现二分类的方法示例

使用TensorFlow构建一个神经网络来实现二分类,主要包括输入数据格式、隐藏层数的定义、损失函数的选择、优化函数的选择、输出层。下面通过numpy来随机生成一组数据,通过定义一种正负...

详解python读取image

python 读取image 在python中我们有两个库可以处理图像文件,scipy和matplotlib. 安装库 pip install matplotlib pillow s...

python返回数组的索引实例

使用python里的index nums = [1, 2, 3, 4, 5, 6, 1, 9] print nums.index(max(nums)) print nums.inde...

python itchat给指定联系人发消息的方法

itchat模块 官方参考文档:https://itchat.readthedocs.io/zh/latest/ 安装 pip install itchat / pip3 insta...