首页 > 解决方案 > 使用顶帽变换时如何旋转结构元素?

问题描述

我正在对图像进行顶帽转换,结构元素长 21 像素,宽 1 像素,如何旋转这个结构元素?所以我可以从该图像中提取不同角度的信息。

我现在拥有的是

import numpy as np
import cv2
element = np.ones((21, 1))

new_image = cv2.morphologyEx(origin_image, cv2.MORPH_TOPHAT, element, iterations = 1)

但是如何将其应用于不同的角度呢?就像将结构元素旋转 30 度一样。

标签: pythonopencvimage-processingopencv3.0

解决方案


我用来旋转结构元素的函数如下:

import cv2 
import numpy
def rotate_bound(image,angle):
    (h,w) = image.shape[:2]
    (cx,cy) = (w/2,h/2)

    M = cv2.getRotationMatrix2D((cx,cy),-angle,1.0)
    print(M.shape)
    print(M)

    cos = np.abs(M[0,0])
    sin = np.abs(M[0,1])

    nW = int((h*sin)+(w*cos))
    nH = int((h*cos)+(w*sin))

    M[0,2] += (nW/2) - cx
    M[1,2] += (nH/2) - cy

    return cv2.warpAffine(image,M,(nW,nH))

element = np.ones((21,1))
rotated_element = rotate_bound(element, 30)
rotated_element[rotated_element == 0] = 10
result = cv2.morphologyEx(image, cv2.MORPH_TOPHAT, rotated_element)

感谢@fmw42 的帮助 :)


推荐阅读