gpt4 book ai didi

python - 如何在opencv中应用三点三角形渐变?

转载 作者:行者123 更新时间:2023-12-02 16:51:11 31 4
gpt4 key购买 nike

假设我们有一个像this one:这样的Delaunay三角剖分

enter image description here

fillConvexPoly上的getVoronoiFacetList产生

里面有可以通过getTriangleList获得的三角形。我想画Delaunay三角剖分
像是由三角形组成的平滑渐变图像,如下所示:

enter image description here

如何在opencv中做这样的事情?

最佳答案

这是在Python / OpenCV中执行此操作的方法,但是它将比我之前介绍的Python / Wand版本慢,因为它必须循环并求解重心坐标的每个像素处的线性最小二乘方程。

import cv2
import numpy as np

# References:
# https://stackoverflow.com/questions/31442826/increasing-efficiency-of-barycentric-coordinate-calculation-in-python
# https://math.stackexchange.com/questions/81178/help-with-cramers-rule-and-barycentric-coordinates

# create black background image
result = np.zeros((500,500,3), dtype=np.uint8)

# Specify (x,y) triangle vertices
a = (250,100)
b = (100,400)
c = (400,400)

# Specify colors
red = (0,0,255)
green = (0,255,0)
blue = (255,0,0)

# Make array of vertices
# ax bx cx
# ay by cy
# 1 1 1
triArr = np.asarray([a[0],b[0],c[0], a[1],b[1],c[1], 1,1,1]).reshape((3, 3))

# Get bounding box of the triangle
xleft = min(a[0], b[0], c[0])
xright = max(a[0], b[0], c[0])
ytop = min(a[1], b[1], c[1])
ybottom = max(a[1], b[1], c[1])

# loop over each pixel, compute barycentric coordinates and interpolate vertex colors
for y in range(ytop, ybottom):

for x in range(xleft, xright):

# Store the current point as a matrix
p = np.array([[x], [y], [1]])

# Solve for least squares solution to get barycentric coordinates
(alpha, beta, gamma) = np.linalg.lstsq(triArr, p, rcond=-1)[0]

# The point is inside the triangle if all the following conditions are met; otherwise outside the triangle
if alpha > 0 and beta > 0 and gamma > 0:
# do barycentric interpolation on colors
color = (red*alpha + green*beta + blue*gamma)
result[y,x] = color

# show results
cv2.imshow('result', result)
cv2.waitKey(0)
cv2.destroyAllWindows()

# save results
cv2.imwrite('barycentric_triange.png', result)

结果:

enter image description here

关于python - 如何在opencv中应用三点三角形渐变?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61854897/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com