Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 597
Osi Avatar asked Jul 10 '19 10:07

Osi


People also ask

How do I half an image in OpenCV?

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.

What is cv2 divide?

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.


2 Answers

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

like image 125
Masoud Avatar answered Oct 11 '22 11:10

Masoud


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

like image 22
Osi Avatar answered Oct 11 '22 12:10

Osi