Python - Rotate Image

前端 未结 5 1752
时光说笑
时光说笑 2021-01-06 17:41

How can I rotate an image in Python with the help of OpenCv library, and by changing the value of height and width of the image (without using the built-in methods for rotat

相关标签:
5条回答
  • 2021-01-06 18:13

    I use the PIL package, it's very simple to do that.

    from PIL import Image
    path = '/Users/diegodsp/sample.jpg'
    img = Image.open(path)
    img = img.rotate(90) # 90, -90, 180, ...
    img.save(path) # to override your old file
    
    0 讨论(0)
  • 2021-01-06 18:15

    If you need a simple rotation in OpenCV, it's built in:

    img=cv2.imread('Images/Screenshot.png',cv2.IMREAD_GRAYSCALE)
    
    imgrot = cv2.rotate(img,cv2.ROTATE_90_CLOCKWISE)
    

    Other possibilities are cv2.ROTATE_90_COUNTERCLOCKWISE and cv2.ROTATE_180

    0 讨论(0)
  • 2021-01-06 18:21

    If you are interested in doing it from scratch then you can use Shear transformation method to rotate image by any arbitary angle. There is a great reference here: https://medium.com/@gautamnagrawal/rotating-image-by-any-angle-shear-transformation-using-only-numpy-d28d16eb5076

    0 讨论(0)
  • 2021-01-06 18:23

    Does it have to be OpenCv? Cause if not you can easily do it with PIL:

    from PIL import Image
    
    def rotate_img(img_path, rt_degr):
        img = Image.open(img_path)
        return img.rotate(rt_degr, expand=1)
    
    img_rt_90 = rotate_img('Images/Screenshot.png', 90)
    img_rt_90.save('img_rt_90.png')
    
    0 讨论(0)
  • 2021-01-06 18:28

    Swap the indexes:

    You can create an empty image with np.zeros() and then read the pixels from your current image to the empty image. You can change the order that you read the pixels to perform some basic rotations. The following examples should help.

    Test image:

    img = cv2.imread('texas_longhorns_log.png')
    

    Rotate left 90 degrees:

    h,w,c = img.shape
    
    empty_img = np.zeros([h,w,c], dtype=np.uint8)
    
    for i in range(h):
        for j in range(w):
            empty_img[i,j] = img[j-1,i-1]
            empty_img = empty_img[0:h,0:w]
    
    cv2.imwrite("tester1.png", empty_img)
    

    Rotate right 90 degrees:

    h,w,c = img.shape
    
    empty_img = np.zeros([h,w,c], dtype=np.uint8)
    
    for i in range(h):
        for j in range(w):
            empty_img[i,j] = img[h-j-1,w-i-1]
            empty_img = empty_img[0:h,0:w]
    
    cv2.imwrite("tester2.png", empty_img)
    

    Rotate 180 degrees:

    h,w,c = img.shape
    
    empty_img = np.zeros([h,w,c], dtype=np.uint8)
    
    for i in range(h):
        for j in range(w):
            empty_img[i,j] = img[h-i-1,w-j-1]
            empty_img = empty_img[0:h,0:w]
    
    cv2.imwrite("tester3.png", empty_img)
    

    0 讨论(0)
提交回复
热议问题