I couldn't find any existing answers on how to do this so I wrote my own code already which is down below. This might not be the fastest way to do it but it works well.
To keep the bottom half we simply do [int(yMax/2):yMax, xMin:xMax] which means from half the image to to the bottom. x is 0 to the max width. Keep in mind that OpenCV starts from the top left of an image and increasing the Y value means downwards.
Performs per-element division of two arrays or a scalar by an array. Divide(InputArray, InputArray, OutputArray, Double, Int32) Performs per-element division of two arrays or a scalar by an array.
numpy.roll()
can be used to to shift an array circularly in any axis. For a 1D array for example, it can be used as:
import numpy as np
arr = np.array(range(10))
# arr = [0 1 2 3 4 5 6 7 8 9]
arr_2 = np.roll(arr, len(arr)//2)
# arr_2 = [5 6 7 8 9 0 1 2 3 4]
The same method can be used to swap two halves of images horizontally:
import cv2
import numpy as np
img = cv2.imread('Figure.png', 0)
img = np.roll(img, img.shape[1]//2, axis = 1)
for swapping vertically, np.roll(img, img.shape[0]//2, axis = 0)
.
Swapping: (required imports: numpy as np, cv2)
height, width = image.shape[0:2]
cutW = int(width / 2)
swapped_image = image[0:height, width - cutW:width].copy()
swapped_image = np.hstack((swapped_image, image[0:height, 0:width-cutW]))
image is the original image that you want to swap. It should be in the OpenCV file format already meaning you should have used cv2.imread() to open the file, or converted it from another image type to opencv
First half width is taken using 1/2 image.shape. This becomes cutW (width)
Then it copies the last half of the image into a new image called "swapped_image"
Then it appends the first half of the original image to the swapped_image using np.hstack
optional: show the images afterwards
height, width = image.shape[0:2]
cutW = int(width / 2)
swapped_image = image[0:height, width - cutW:width].copy()
swapped_image = np.hstack((swapped_image, image[0:height, 0:width-cutW]))
cv2.imshow("SwappedImage", swapped_image)
cv2.imshow("Original ", image)
cv2.waitKey(0)
cv2.destroyAllWindows()
If you want to swap vertically you could do the same with np.vstack
and selecting half of the height original image instead of the width
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With