Osi
Osi

Reputation: 448

How to horizontally swap two halves of an image in python opencv

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.

Upvotes: 8

Views: 2114

Answers (2)

Masoud
Masoud

Reputation: 1280

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).

Upvotes: 4

Osi
Osi

Reputation: 448

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

Upvotes: 4

Related Questions