我想在我定义的函数中旋转图像并将结果保存在参数中,以便在主函数中额外使用。
代码如下:
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/