i am trying to rotate an image at 45 degrees in the center of rotation but i am having a problem achieving it in the center by using any two given coordinates such as [0,0]

expecting a 45 dgrees at the center using any two given coordinates

#Pivot is the coordonates for the center of rotation
def rotateImage(self, img, angle, pivot):
    padX = int(pivot[1] - img.shape[1] / 2)
    padY = int(pivot[0] - img.shape[0] / 2)
    x1, x2, y1, y2 = 0,0,0,0
    if(pivot[1] > img.shape[1]/2):
        img = pad(img, ((0,0),(0, padX)), 'constant', constant_values=1)
        x2=padX
    elif(pivot[1] < img.shape[1]):
        img = pad(img, ((0,0),(abs(padX), 0)), 'constant', constant_values=1)
        x1=abs(padX)

    if (pivot[0] > img.shape[0] / 2):
        img = pad(img, ((0, padY), (0, 0)), 'constant', constant_values=(1,1))
        y2=padY
    elif (pivot[0] < img.shape[0]):
        img = pad(img, ((abs(padY), 0), (0, 0)), 'constant', constant_values=(1,1))
        y1=abs(padY)

    imgR = ndimage.rotate(img, angle, reshape=False, cval=1)
    return imgR[y1: imgR.shape[0]-y2, x1: imgR.shape[1]-x2]
try:
    angle = float(self.rotation_value.toPlainText())
except:
    angle = 0
if (angle <= 360 and angle >= -360 and angle != 0):
    corrected = self.rotateImage(corrected, angle, [0, 0])

writeraw32(self.path_ImageJ + "/temp/LE_corr_rot.raw", corrected)
1

There are 1 best solutions below

0
koegl On

I'm not sure what's wrong with your code, but here's a simple way of doing it with opencv (you can install it with pip install opencv-python)

import cv2
import matplotlib.pyplot as plt


# Load the image
image = cv2.imread('image.png')

# Define the angle of rotation (in degrees) and the center of rotation
angle = 45
center = (10, 10)

# Calculate the rotation matrix
rotation_matrix = cv2.getRotationMatrix2D(center, angle, 1)  # 1 is the scale

# Rotate the image
rotated_image = cv2.warpAffine(image, rotation_matrix, image.shape[:2])

# Display the image - or write the image with your code
plt.imshow(rotated_image)
plt.show()