【问题标题】:How to rotate all the object in vertical orientation?如何在垂直方向旋转所有对象?
【发布时间】:2021-11-08 02:12:22
【问题描述】:

图像中的对象处于不同的方向。我想改变垂直方向的所有对象方向。代码如下所示。代码并非所有面向对象都是垂直的。 [Image]

image = cv2.imread(r'C:\Users\Desktop\Sam.jpg')
Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# create a binary  image
_, binary = cv2.threshold(Gray, 127, 255, cv2.THRESH_BINARY_INV)
# find the contours from the binary image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
[-2:]
           
for i in range(len(contours)):            
    rect = cv2.minAreaRect(contours[i])             
    angle=rect[2]
    print('rect',rect)
    print('ANgle:',angle)
    
  
    if angle>0:
        rangle =  90-angle
        print('rangle:',rangle)
    else:
        rangle =angle
        print('rangle:',rangle)
    rotate_img=  ndimage.rotate(cimg, rangle,reshape=True)
    print('rotate_img shape:',rotate_img.shape)
    plt.figure(figsize=(8, 8))
    plt.title('rotate_img')
    plt.imshow(rotate_img, cmap='gray')
    plt.show()

【问题讨论】:

  • 如何对图像进行阈值处理并使用skimage.label 查找图像中的每个组件。接下来,找到每个组件的质心和围绕它的边界框。在 ROI 中找到对象的角度并旋转对象,使其垂直。最后将旋转后的 ROI 粘贴到旧图像或新图像上,使旋转对象的质心位于原始对象的质心。
  • @yannziselman 谢谢你的建议。是的,我想找到旋转角度,使图像中的对象始终垂直。
  • 您可以通过查找属于对象的像素的 x 索引与其 y 索引之间的相关性来找到角度
  • @yannziselman 能否详细描述一下。

标签: image image-processing computer-vision rotation image-rotation


【解决方案1】:

要在垂直方向旋转对象,我们首先需要找到对象的方向。 OpenCV 提供了一个函数 cv2.minAreaRect() 来找到最小面积矩形的中心,(高度,宽度)和旋转角度。高度必须大于宽度才能处于垂直方向。仅旋转角度对于垂直方向是不够的。由于以下原因,旋转角度重复 -0 到 -90。更多细节在这里:the ai learnernamkeenman

  • 矩形的最低点是第 0 个顶点,第 1、2、3 个顶点 顶点顺时针。

  • 高度是第 0 和第 1(或第 2 和第 3)顶点之间的距离。

  • 宽度是第 1 和第 2(或第 0 和第 3)顶点之间的距离。

  • 旋转的角度是线之间的角度(加入起点和 端点)和水平方向。

image = cv2.imread(r'C:\Users\Desktop\Sam.jpg')
Gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Create a binary threshold image
_, binary = cv2.threshold(Gray, 127, 255, cv2.THRESH_BINARY_INV)
# Find the contours from the binary image
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE) 
[-2:]
           
for i in range(len(contours)):
    rect = cv2.minAreaRect(contours[i])              
    angle=rect[2]
    rwidth,rheight=rect[2]
    if rheight>rwidth :
        rangle =  angle
        print('rangle:',rangle)
    else:
        rangle =90-abs(angle)
        print('rangle:',rangle)
    rotate_img=  ndimage.rotate(cimg, rangle,reshape=True)
    print('rotate_img shape:',rotate_img.shape)
    plt.figure(figsize=(8, 8))
    plt.title('rotate_img')
    plt.imshow(rotate_img, cmap='gray')
    plt.show()

【讨论】:

  • 请对您的回答提供一些解释,以便其他人更容易理解您是如何解决问题的
  • 正如目前所写,您的答案尚不清楚。请edit 添加其他详细信息,以帮助其他人了解这如何解决所提出的问题。你可以找到更多关于如何写好答案的信息in the help center
  • 感谢 yuki 和社区,让我注意到这一点。我已对答案进行了详细更改。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-12-28
  • 2013-01-04
  • 2020-01-30
  • 1970-01-01
相关资源
最近更新 更多