【问题标题】:How to rotate all the images to the same orientation?如何将所有图像旋转到相同的方向?
【发布时间】:2021-02-24 13:25:48
【问题描述】:

我正在尝试执行图像分类任务并希望确保我的输入数据都具有相同的方向。 下面的代码没有将所有图像匹配到相同的方向,并且有些翻转错误。 如果有人能帮助我解决这个问题,我将不胜感激,谢谢 original image 1
original image 2

import cv2
import numpy as np
import matplotlib.pyplot as plt
def getSubImage(rect, image):
    center, size, theta = rect
    center, size = tuple(map(int, center)), tuple(map(int, size))
    M = cv2.getRotationMatrix2D( center, theta, 1)
    dst = cv2.warpAffine(image, M, src.shape[:2])
    out = cv2.getRectSubPix(dst, size, center)
    return out

image = cv2.imread('orginal1.png')
im_bw = cv2.cvtColor(image, cv2.COLOR_RGB2GRAY)
blur = cv2.GaussianBlur(im_bw, (5,5), 0)
im_bw = cv2.Canny(blur, 10, 90)
contours, hierarchy = cv2.findContours(im_bw, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
rect = cv2.minAreaRect(contours[0])

out = getSubImage(rect, image)
cv2.imwrite('rotedorginal1.jpg', out)
plt.imshow(out)
plt.show()

【问题讨论】:

  • 请正确缩进您的代码。

标签: python python-3.x opencv


【解决方案1】:

您只需要使用cv2.getRotationMatrix2D 构建将图像旋转直角的矩阵,并使用cv2.warpAffine 对矩阵进行运算:

(x, y), (w, h), angle = cv2.minAreaRect(contours[0])
result = cv2.warpAffine(image, cv2.getRotationMatrix2D((image.shape[1]//2, image.shape[0]//2), angle-90, 1), (image.shape))

上面的代码转换了这张图片:

进入这个:

【讨论】:

  • 谢谢卡洛斯。当我运行上面的代码时,一些图像将被垂直校正,而一些图像将保持水平。我们需要的是使所有图像垂直
  • 旋转角度由getRotationMatrix2D((x,y), angle, scale)中的第二个参数控制。我在上面的示例中使用了角度 90,但您可能需要找到正确旋转所有图像的值。另外,请考虑到 minAreaRect 函数计算的角度可能与您的想法相反(旋转 180 度)。这就是为什么仅用一个例子来计算角度的函数并不容易。此外,OpenCV 的 0 度参考是单位圆中的 90 度轴,可以说是 y 轴。这需要在角度上进行额外的工作。
  • 是的,我现在正在尝试。此外,我试图基于轴 y 和 x 旋转,这可以提供更好的结果。谢谢
  • Ibra,如果我的回答对你有帮助,请考虑接受它作为正确答案,谢谢!
猜你喜欢
  • 2020-09-08
  • 2021-11-22
  • 2019-09-27
  • 2020-02-24
  • 2014-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多