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

yipeiwu_com5年前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将pandas datarame保存为txt文件的实例

CSV means Comma Separated Values. It is plain text (ansi). The CSV ("Comma Separated Value")...

Python itertools模块详解

这货很强大, 必须掌握 文档 链接 http://docs.python.org/2/library/itertools.html pymotw 链接 http://pymotw.com...

Python:Numpy 求平均向量的实例

如下所示: >>> import numpy as np >>> a = np.array([[1, 2, 3], [3, 1, 2]]) >...

Python中的filter()函数的用法

Python内建的filter()函数用于过滤序列。 和map()类似,filter()也接收一个函数和一个序列。和map()不同的时,filter()把传入的函数依次作用于每个元素,然...

PyQt5每天必学之切换按钮

PyQt5每天必学之切换按钮

切换按钮是QPushButton的特殊模式。它是一个具有两种状态的按钮:按压和未按压。我们通过这两种状态之间的切换来修改其它内容。 #!/usr/bin/python3 # -*-...