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
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
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
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
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')
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.
img = cv2.imread('texas_longhorns_log.png')
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)
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)
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)