Reputation: 83
I want to mirror an image in python but this error occur
Exception has occurred: IndexError
index -751 is out of bounds for axis 1 with size 750
File "D:\PART 1\Miror.py", line 20, in <module>
d=img.item(i,mn,0)
this is my code
img = cv2.imread('D:\\PART 1\\gwk.jpg')
tinggi = img.shape[0]
lebar = img.shape[1]
brightness = 100
nm=int(tinggi-1)
mn=int(lebar-1)
lebarBaru= int(lebar/2)
tinggiBaru= int(tinggi/2)
for i in np.arange(tinggiBaru):
for j in np.arange(lebarBaru):
a=img.item(i,j,0)
b=img.item(i,j,1)
c=img.item(i,j,2)
d=img.item(i,mn,0)
e=img.item(i,mn,1)
f=img.item(i,mn,2)
img.itemset((i,j,0),d)
img.itemset((i,j,1),e)
img.itemset((i,j,2),f)
img.itemset((i,mn,0),a)
img.itemset((i,mn,1),b)
img.itemset((i,mn,2),c)
mn-=1
I want to mirror an image in python without using OpenCV function for mirroring an image
Upvotes: 2
Views: 12604
Reputation: 10890
Just invert the direction of one (or both if you like) dimensions of the image array.
Example with imageio
, but should work the same with similar image arrays, too, like e.g. in opencv
:
import matplotlib.pyplot as plt
import imageio
im = imageio.imread('imageio:chelsea.png')
fig, axs = plt.subplots(1, 3, sharey=True)
axs[0].imshow(im)
axs[1].imshow(im[:, ::-1, :])
axs[2].imshow(im[::-1, :, :])
Upvotes: 5
Reputation: 18925
If you're willing to use NumPy (OpenCV uses NumPy arrays for storing images), use it's flip
method. Otherwise, you can also just use the underlying array indexing using ::-1
notation.
Here's an example for mirroring in x direction (flip horizontally), y direction (flip vertically), and both directions (flip horizontally and vertically):
import cv2
import numpy as np
# Read input image
img = cv2.imread('path/to/your/image.png')
# Mirror in x direction (flip horizontally)
imgX = np.flip(img, axis=1)
# imgX = imgX = img[:, ::-1, :]
# Mirror in y direction (flip vertically)
imgY = np.flip(img, axis=0)
# imgY = img[::-1, :, :]
# Mirror in both directions (flip horizontally and vertically)
imgXY = np.flip(img, axis=(0, 1))
# imgXY = img[::-1, ::-1, :]
# Outputs
cv2.imshow('img', img)
cv2.imshow('imgX', imgX)
cv2.imshow('imgY', imgY)
cv2.imshow('imgXY', imgXY)
cv2.waitKey(0)
(Exemplary input and outputs are omitted here...)
Hope that helps!
Upvotes: 4