使用 OpenCV 填充四边形时避免锯齿状边缘

问题描述 投票:0回答:1

我试图填充图像上由四边形标识的区域,但在执行填充后不断出现锯齿状线条(无论我使用图像填充还是仅使用纯黑色填充似乎并不重要)。我认为这是由于抗锯齿所致,所以我使用了

lineType=cv2.LINE_AA
,但我仍然可以看到锯齿状边缘。

问:有没有办法避免这些锯齿状边缘并产生平滑的直线?

下面是我正在使用的代码:

import cv2
import numpy as np

# Load the mockup image
mockup = cv2.imread('mockup3.png')

# Define the quadrilateral coordinates (x, y) in clockwise order
quad_coords = np.array([
    [307.7142857142857, 239.8571428571429],
    [300.57142857142856, 875.5714285714286],
    [742.3529411764706, 875.2941176470589],
    [736.2857142857143, 239.8571428571429]
], dtype=np.float32)

# Create an empty mask to fill with the smoothed quadrilateral region
mask = np.zeros(mockup.shape[:2], dtype=np.uint8)

# Draw a filled smoothed quadrilateral on the mask
cv2.fillPoly(mask, [quad_coords.astype(np.int32)], (255, 255, 255), lineType=cv2.LINE_AA)

# Create a black image of the same size as the mockup
black_background = np.zeros_like(mockup)

# Overlay the black background onto the mockup using the smoothed mask
result = cv2.bitwise_and(mockup, mockup, mask=~mask)
result += cv2.bitwise_and(black_background, black_background, mask=mask)

# Save the final result
cv2.imwrite('output.png', result)

输入图像:

输出图像(有问题的区域以红色突出显示):

python numpy opencv image-processing
1个回答
0
投票

Chris 的部分观点是,抗锯齿是通过模糊所绘制内容的边缘来完成的。通过在蒙版上执行此操作,然后执行 AND,您可以消除模糊边缘(按位 AND 仅输出 1 或 0)。您可以通过将抗锯齿多边形直接绘制到图像上来获得平滑的边缘。

import cv2
import numpy as np

# Load the mockup image
mockup = cv2.imread('mockup.png')

# Define the quadrilateral coordinates (x, y) in clockwise order
quad_coords = np.array([
    [307.7142857142857, 239.8571428571429],
    [300.57142857142856, 875.5714285714286],
    [742.3529411764706, 875.2941176470589],
    [736.2857142857143, 239.8571428571429]
], dtype=np.float32)

# Draw a filled smoothed quadrilateral on the mask
cv2.fillPoly(mockup, [quad_coords.astype(np.int32)], (0, 0, 0), lineType=cv2.LINE_AA)

# Save the final result
cv2.imwrite('output.png', result)

如果您想用图像替换框架,您仍然可以像以前一样绘制蒙版,但不能使用二元运算来覆盖蒙版。你想要一个加权

© www.soinside.com 2019 - 2024. All rights reserved.