【问题标题】:Python OpenCV - File rotating, but color values are overwrittenPython OpenCV - 文件旋转,但颜色值被覆盖
【发布时间】:2014-02-22 03:09:39
【问题描述】:

我正在试验 OpenCV 和 Python 的绑定。此代码旨在使用命令行参数值旋转图像。但是,它保存为输入图像的精确副本,没有任何旋转。

这个代码是adapted from this answer

import cv2 as cv

def rotateImage(self, image, angle):
    print "Rotating image to angle: %s" % (angle)

    print type(image) #image is numpy.ndarray
    print type(angle) #angle is float

    center = tuple(np.array(image.shape[0:2])/2)
    matrix = cv.getRotationMatrix2D(center, angle, 1.0)
    rotate = cv.warpAffine(image, matrix, image.shape[0:2], flags=cv.INTER_LINEAR)

    fileList = self.filename.split(".")
    newFile = fileList[0] + "_rotate_%s." % (int(angle)) + fileList[1]

    print "Saving to %s" % (newFile)
    cv.imwrite(newFile, rotate)

我的问题是旋转后保存的图像不是输入的图像。

输入图片:

输出:

鉴于这些输入和输出,我如何更改图像尺寸以允许 30 度和 45 度旋转?

【问题讨论】:

    标签: python opencv image-processing image-rotation


    【解决方案1】:

    问题在于,旋转后,您的图像会超出原始形状的边缘。解决办法是把原图拉长再旋转。这样,重要的部分就不会被切断:

    import cv2 as cv
    import numpy as np
    
    def extend(image):
        nrow, ncol, ncolor = image.shape
        n = int((nrow**2 + ncol**2)**.5//2 + 1)
        new = np.zeros((2*n, 2*n, ncolor))
        a = nrow//2
        b = ncol//2
        new[n-a:n-a+nrow, n-b:n-b+ncol, :] = image
        return new
    
    def rotateImage(fname, angle):
        print "Rotating image to angle: %s" % (angle)
    
        image = cv.imread(fname, -1)
        print type(image) #image is numpy.ndarray
        print type(angle) #angle is float
        image = extend(image)
    
        center = tuple(np.array(image.shape[0:2])/2)
        matrix = cv.getRotationMatrix2D(center, angle, 1.0)
        rotate = cv.warpAffine(image, matrix, image.shape[0:2], flags=cv.INTER_LINEAR)
    
        fileList = fname.split(".")
        newFile = fileList[0] + "_rotate_%s." % (int(angle)) + fileList[1]
    
        print "Saving to %s" % (newFile)
        cv.imwrite(newFile, rotate)
    

    extend 函数创建一个更大的数组(大小基于原始图像的对角线)并将原始图像放在中心。我用 np.zeros 创建了更大的图像,这意味着扩展返回的图像有一个大的黑色边框。此扩展需要在图像旋转之前完成。

    旋转 45 度后,您的图像如下所示:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-04-25
      • 2018-12-19
      • 2023-02-26
      • 1970-01-01
      • 2018-11-12
      • 2014-08-02
      • 1970-01-01
      相关资源
      最近更新 更多