The object in the image are in different orientation. I want to change all object orientation in vertical. The code is shown below. The code doesn't all object orientation to vertical. [Image]
image = cv2.imread(r'C:\Users\Desktop\Sam.jpg')
Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# create a binary image
_, binary = cv2.threshold(Gray, 127, 255, cv2.THRESH_BINARY_INV)
# find the contours from the binary image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
[-2:]
for i in range(len(contours)):
rect = cv2.minAreaRect(contours[i])
angle=rect[2]
print('rect',rect)
print('ANgle:',angle)
if angle>0:
rangle = 90-angle
print('rangle:',rangle)
else:
rangle =angle
print('rangle:',rangle)
rotate_img= ndimage.rotate(cimg, rangle,reshape=True)
print('rotate_img shape:',rotate_img.shape)
plt.figure(figsize=(8, 8))
plt.title('rotate_img')
plt.imshow(rotate_img, cmap='gray')
plt.show()
CodePudding user response:
To rotate objects in the vertical orientation, we first need to find the orientation of a object. OpenCV provides a function cv2.minAreaRect() to find minimum area rectangle's center,(height, width)and angle of rotation. Height must be larger than width to be in the vertical orientation. The angle of rotation only is not enough for the vertical orientation. The angle of rotation reiterating -0 to -90 because of following reason. More detail here: the ai learner and namkeenman
The lowest point in a rectangle is 0th vertex, and 1st, 2nd, 3rd vertices follow clockwise.
Height is distance between 0th & 1st (or 2nd & 3rd) vertices.
Width is distance between 1st & 2nd (or 0th & 3rd) vertices.
The angle of rotation is angle between the line (joining the starting and endpoint) and the horizontal.
image = cv2.imread(r'C:\Users\Desktop\Sam.jpg')
Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create a binary threshold image
_, binary = cv2.threshold(Gray, 127, 255, cv2.THRESH_BINARY_INV)
# Find the contours from the binary image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
[-2:]
for i in range(len(contours)):
rect = cv2.minAreaRect(contours[i])
angle=rect[2]
rwidth,rheight=rect[2]
if rheight>rwidth :
rangle = angle
print('rangle:',rangle)
else:
rangle =90-abs(angle)
print('rangle:',rangle)
rotate_img= ndimage.rotate(cimg, rangle,reshape=True)
print('rotate_img shape:',rotate_img.shape)
plt.figure(figsize=(8, 8))
plt.title('rotate_img')
plt.imshow(rotate_img, cmap='gray')
plt.show()