1

我想在 python 中镜像一个图像,但是发生了这个错误

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)

这是我的代码

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

我想在 python 中镜像图像而不使用 OpenCV 函数来镜像图像

4

2 回答 2

5

只需反转图像阵列的一个(或两个,如果你喜欢)维度的方向。

的示例imageio,但也应该与类似的图像数组相同,例如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, :, :])

在此处输入图像描述

于 2019-09-20T07:00:10.393 回答
1

如果您愿意使用 NumPy(OpenCV 使用 NumPy 数组来存储图像),请使用它的flip方法。否则,您也可以使用::-1符号来使用底层数组索引。

这是在 x 方向(水平翻转)、y 方向(垂直翻转)和两个方向(水平和垂直翻转)进行镜像的示例:

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)

(此处省略示例性输入和输出...)

希望有帮助!

于 2019-09-20T06:58:33.400 回答