python - 在我用 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!")

保存在函数“rotate”中的结果“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!")

关于python - 在我用 Python 定义的函数中通过 opencv 旋转图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37246440/

相关文章:

python - 将 C 函数转换为 Python3 形式?

python - 类中的嵌套字典

python - 具有复杂项目结构的Docker设置

opencv - 如何在轮廓上找到具有特定度数的点(Opencv)

java - opencv库支持哪些android API?

python - 默认情况下 SecureSocial 为 SecureSocialPasswordHasher 使用什么加密?

python - 清除 `deque` s : is it thread-safe?

c++ - 使用 OpenCV 2.4.8 构建 CUDA 5.5

c++ - OpenCV:图像窗口一直挂起并且没有响应

java - JavaCV 中的 ExceptionInInitializerError