使用Python在我定义的函数中通过opencv旋转图像

问题描述:

我想在我定义的函数中旋转图像并将结果保存在主函数中额外使用的参数中。使用Python在我定义的函数中通过opencv旋转图像

的代码如下:

import cv2 

def rotate(img1, img2): # rotate img1 and save it in img2 
    angle = 30 # rotated angle 
    h, w, c = img1.shape 

    m = cv2.getRotationMatrix2D((w/2, h/2), angle, 1) 
    img2 = cv2.warpAffine(img1, m, (w, h)) # rotate the img1 to img2 
    cv2.imwrite("rotate1.jpg", img2) # save the rotated image within the function, successfully! 

img = cv2.imread("test.jpg") 
img_out = None 

rotate(img, img_out) 

cv2.imwrite("rotate2.jpg", img_out) # save the rotated image in the main function, failed! 

print("Finished!") 

结果 “IMG2” 保存功能 “旋转” 是确定的。 但是函数参数中的一个“img_out”无法保存。

它有什么问题?我怎样才能解决它而不使用全局变量?谢谢!

修改函数中执行的参数不会返回到主程序。你也可以看看here进一步阅读。

你可以做的是返回一个图像显示在下面的代码:

import cv2 

def rotate(img1): # rotate img1 and save it in img 
    angle = 30 # rotated angle 
    h, w, c = img1.shape 

    m = cv2.getRotationMatrix2D((w/2, h/2), angle, 1) 
    img2 = cv2.warpAffine(img1, m, (w, h)) # rotate the img1 to img2 
    cv2.imwrite("rotate1.jpg", img2) # save the rotated image within the function, successfully! 
    return img2 

img = cv2.imread("image.jpg") 

img_out=rotate(img) 

cv2.imwrite("rotate2.jpg", img_out) # save the rotated image in the main function, failed! 

print("Finished!")