python opencv 找出图像中的最大轮廓并填充(生成mask)

mask = np.ones_like(img_stack)
for i in range(num):
    # 阈值化
    _, binaryzation = cv2.threshold(img_stack[i], 5, 255, cv2.THRESH_BINARY_INV)
    # 找到所有的轮廓
    contours, _ = cv2.findContours(binaryzation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    area = []
    # 找到最大的轮廓
    for k in range(len(contours)):
        area.append(cv2.contourArea(contours[k]))
    max_idx = np.argmax(np.array(area))
    # cv2.fillContexPoly(mask[i], contours[max_idx], 0)
    # 填充最大的轮廓
    cv2.drawContours(mask[i], contours, max_idx, 0, cv2.FILLED)
    del area 



def _write_mask(mask, i):
    Image.fromarray(mask.astype(np.uint8)*255).save(os.path.join(path, 'm%d.png' % i))

num_cores = 10
parallel = Parallel(n_jobs=num_cores, backend='threading')
parallel(delayed(_write_mask)(mask[i, :, :], i) for i in range(0, num))

 

你可能感兴趣的:(opencv与python)