Rotate the image via opencv in my defined function with Python
Question: I would like to rotate an image in my defined function and save the result in
parameter for extra use in main function.

The codes are as below:

    
    
    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!")
    

The result "img2" saved in function "rotate" is ok. But the one "img_out" from
the function parameter is failed to save.

What's the problem with it? How can I resolve it without using the global
variable? Thanks!


Answer: Modifications of parameters performed within a function will not be returned
to the main program. You could also have a look
[here](http://stackoverflow.com/questions/575196/in-python-why-can-a-function-
modify-some-arguments-as-perceived-by-the-caller) for further reading.

What you can do is return an image as shown in the code below:

    
    
    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!")
    

