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 rotation in OpenCv). It has to implement with two nested for loop.
img=cv2.imread('Images/Screenshot.png',cv2.IMREAD_GRAYSCALE)
height, width = img.shape
# for i in range(0,height):
# for j in range(0,width):
# img[i][j]=
# show rotated image
cv2.imshow("image",img)
Thanks for taking your time to help me!
解决方案
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)