zl程序教程

您现在的位置是:首页 >  后端

当前栏目

如何在OpenCV Python中翻转图像?

PythonOpencv 如何 图像 翻转
2023-09-11 14:18:27 时间

在 OpenCV 中,可以使用函数 cv2.flip() 翻转图像。使用此功能,我们可以在 X 轴、Y 轴和两个轴上翻转图像。它接受标志翻转代码作为参数,以在轴上翻转图像。

如果翻转代码设置为 0,则图像在 x 轴上翻转,如果翻转代码设置为正整数(例如 1),则图像在 Y 轴上翻转。如果 flipCode 设置为负整数(例如“-1”),则图像将在两个轴上翻转。

步骤

要翻转图像,可以按照以下步骤操作 -

  • 导入所需的库。在以下所有示例中,所需的 Python 库是 OpenCV。确保您已经安装了它。

  • 使用 cv2.imread() 方法读取输入图像。使用图像类型(即.png或jpg)指定图像的完整路径

  • 在输入图像 img 上应用 cv2.flip() 函数。传递参数翻转代码以获得所需的翻转。我们设置 flipCode=0 以围绕 x 轴翻转。

img_v = cv2.flip(img, 0)
  • 显示翻转的输出图像。

在以下示例中,我们将使用此图像作为输入文件 -

 

在这个 Python 程序中,我们将输入图像翻转到 x 轴(垂直)。

 

# import required library import cv2 # read input image img = cv2.imread('blue-car.jpg') # flip the image by vertically img_v = cv2.flip(img, 0) # display the rotated image cv2.imshow("Vertical Flip", img_v) cv2.waitKey(0) cv2.destroyAllWindows()

输出

当你运行上面的程序时,它将产生以下输出窗口 -

请注意,输出图像在 X 轴上翻转。

在这个 Python 程序中,我们将输入图像翻转到 y 轴上(水平)。

 

# import required library import cv2 # read input image img = cv2.imread('blue-car.jpg') # flip the image by horizontally img_h = cv2.flip(img, 1) # display the rotated image cv2.imshow("Horizontal Flip", img_h) cv2.waitKey(0) cv2.destroyAllWindows()

输出

当你运行上面的程序时,它将产生以下输出窗口 -

 

请注意,输出图像在 Y 轴上翻转。

在这个 Python 程序中,我们在两个轴上(垂直和水平)翻转输入图像。

 

# import required library import cv2 # read input image img = cv2.imread('blue-car.jpg') # rotate the image both vertically and horizontally img_vh = cv2.flip(img, -1) # display the rotated image cv2.imshow("Both vertical and horizontal flip", img_vh) cv2.waitKey(0) cv2.destroyAllWindows()

输出

当你运行上面的程序时,它将产生以下输出窗口 -

请注意,输出图像在 X 轴和 Y 轴上翻转。