将[UInt8]强制转换为另一个数组中结构的参数

时间:2018-12-26 01:27:19

标签: arrays class dictionary functional-programming swift4

我希望我的函数可以像在“ setLevel”函数中一样来设置var“通道”的所有“选定”电平。理想情况下,将其内置到我的map / zip函数中会很酷,因为函数始终是一等公民。

def get_trace_list(img, debug=False):
    """
    :param img:
    :return:
    """
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    lower_red = np.array([0, 5, 150])
    upper_red = np.array([8, 210, 255])
    mask0 = cv2.inRange(hsv, lower_red, upper_red)

    lower = np.array([150, 5, 150])
    upper = np.array([180, 210, 255])
    mask1 = cv2.inRange(hsv, lower, upper)

    mask = mask0 + mask1

    only_red_color = cv2.bitwise_and(img, img, mask=mask)

    _, red_color_fix = cv2.threshold(cv2.cvtColor(only_red_color, cv2.COLOR_BGR2GRAY), 0, 255, cv2.THRESH_BINARY)

    kernel = cv2.getStructuringElement(cv2.MORPH_CROSS, (3, 3))
    dilated = cv2.dilate(cv2.medianBlur(red_color_fix, 3), kernel, iterations=9)
    cv2.imshow('dilated', dilated)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    _, contours, hierarchy = cv2.findContours(dilated, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    check_imgs = []
    for index, contour in enumerate(contours):
        con_len = cv2.arcLength(contour, True)
        if con_len > 200:
            [x, y, w, h] = cv2.boundingRect(contour)
            check_imgs.append(red_color_fix[y:y+h, x:x+w])
            if debug:
                cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 255), 2)
                cv2.imwrite('./questions/%s.png' % index, red_color_fix[y:y+h, x:x+w])
    if debug:
        cv2.imwrite('./questions/question.png' , img)
    return check_imgs

1 个答案:

答案 0 :(得分:0)

您可以使用channelsnewArray进行另一个压缩:

public func setLevels(_ newVal: UInt8, forChannels selections: [Bool], array oldArray: [UInt8]) -> [Channel] {
    let newArray = zip(oldArray, selections).map {
        (oldVal, flag) in flag ? newVal : oldVal

    }
    return zip(channels, newArray).map { $0.0.withLevel($0.1) }
}

其中withLevelChannel中的方法:

public func withLevel(_ level: UInt8) -> Channel {
    var copy = self
    copy.level = level
    return copy
}