确定三角形内的所有离散点

时间:2016-05-12 08:50:38

标签: python algorithm

问题输入由三个点A, B, C指定,每个点有两个坐标x, y

解决方案应该是具有自然坐标的三角形内所有点的数组。

实施例: enter image description here

输入是: A, B, C

输出是: 图中的所有命名点

请注意,我试图计算所有不计算的点数,因此this question与我的不同点很多。

我遇到了什么问题:

主要问题在于,指定所有三个段需要为所有段计算系数a, b,这可能会扩展我的代码,因为我必须覆盖所有水平和垂直线的情况。

那么我能提出的最佳方法是:

  1. 从点x'es的最小x到自然A, B, C的自然y's迭代
  2. 从点y的最小A, B, C到自然numpy的自然def get_weight(spot) frame = spot.at_css("table[id='1']").css("tr")[1] starter = frame.at('tr:contains("D7r5")') return nil if starter == nil starter = starter.next_element peso = [] until starter.css("td")[1].nil? data = starter.css("td")[1].inner_html.gsub(/\t{0..100}/, "").strip ndecimal = data.scan(/[0-9]{1,4},?.?[0-9]{0,3}/).last.gsub(",", ".") nmeasure = data.scan(/[kK][Gg]|\s[g]\s|[g]/).last case nmeasure when (/[kK][Gg]/) peso << ndecimal.to_f when (/g|\s[g]\s|[g]/) peso << ndecimal.to_f / 1000 end starter.next_element.nil? ? break : starter = starter.next_element end return peso.max == 0 ? nil : peso.max end 迭代
  3. 对于检查是否满足具有9个不等式的方程组的每个点,我可以手动解决使用@IBOutlet weak var img: UIImageView! var currentnImageIndex:NSInteger = 0 let arrayOfImages = ["Home Filled-50","Bullish-50","Line Chart Filled-50","Stack of Photos Filled-50","News-50","Download From Ftp Filled-50","Administrator Male Filled-50","Trophy Filled-50","Page Overview Filled-50"] override func viewDidLoad() { super.viewDidLoad() img.userInteractionEnabled = true//do not forget to right this line otherwise ...imageView's image will not move let swipeRight = UISwipeGestureRecognizer(target: self, action: "swipedRight:") swipeRight.direction = UISwipeGestureRecognizerDirection.Right img.addGestureRecognizer(swipeRight) let swipeLeft = UISwipeGestureRecognizer(target: self, action: "swipedRight:") swipeLeft.direction = UISwipeGestureRecognizerDirection.Left img.addGestureRecognizer(swipeLeft) img.image = UIImage(named: arrayOfImages[currentnImageIndex]) // Do any additional setup after loading the view. } func swipedRight(gesture : UIGestureRecognizer){ if let swipeGesture = gesture as? UISwipeGestureRecognizer{ switch swipeGesture.direction{ case UISwipeGestureRecognizerDirection.Right: print("User swiped right") if currentnImageIndex < arrayOfImages.count - 1 { ++currentnImageIndex } if currentnImageIndex < arrayOfImages.count { img.image = UIImage(named: arrayOfImages[currentnImageIndex]) } case UISwipeGestureRecognizerDirection.Left: print("User swiped left") // --currentnImageIndex if currentnImageIndex > 0{ --currentnImageIndex } if currentnImageIndex >= 0{ img.image = UIImage(named: arrayOfImages[currentnImageIndex]) } // if curretnImageIndex default: break } ` 。大量的不平等是第二最难的问题。
  4. 一般来说,任何我能想到这样做的方法都需要我编写很多的代码,并带来很多可能的错误。我写的指令越多,性能越低,因为使用了许多非平凡的计算方法。

    非常感谢任何有关更简单解决方案的帮助。

3 个答案:

答案 0 :(得分:1)

你肯定需要三角光栅化。

enter image description here enter image description here

Arbitrary article。您可以更正每条扫描线的起点和终点,以确保它们位于三角形内。

答案 1 :(得分:1)

您可以通过每对点(AB,BC,AC线)找到线,并检查这些线的哪一侧是三角形的内侧。所有线的内侧和侧面上的点都在三角形内:

def insidetriangle((x1,x2,x3),(y1,y2,y3)):
    import numpy as np
    xs=np.array((x1,x2,x3),dtype=float)
    ys=np.array((y1,y2,y3),dtype=float)

    # The possible range of coordinates that can be returned
    x_range=np.arange(np.min(xs),np.max(xs)+1)
    y_range=np.arange(np.min(ys),np.max(ys)+1)

    # Set the grid of coordinates on which the triangle lies. The centre of the
    # triangle serves as a criterion for what is inside or outside the triangle.
    X,Y=np.meshgrid( x_range,y_range )
    xc=np.mean(xs)
    yc=np.mean(ys)

    # From the array 'triangle', points that lie outside the triangle will be
    # set to 'False'.
    triangle = np.ones(X.shape,dtype=bool)
    for i in range(3):
        ii=(i+1)%3
        if xs[i]==xs[ii]:
            include = X *(xc-xs[i])/abs(xc-xs[i]) > xs[i] *(xc-xs[i])/abs(xc-xs[i])
        else:
            poly=np.poly1d([(ys[ii]-ys[i])/(xs[ii]-xs[i]),ys[i]-xs[i]*(ys[ii]-ys[i])/(xs[ii]-xs[i])])
            include = Y *(yc-poly(xc))/abs(yc-poly(xc)) > poly(X) *(yc-poly(xc))/abs(yc-poly(xc))
        triangle*=include

    # Output: 2 arrays with the x- and y- coordinates of the points inside the
    # triangle.
    return X[triangle],Y[triangle]

在循环中解决了3个不等式,导致布尔数组相乘,只得到三角形内的点。

编辑: 循环可以写成更加不言自明的:

for i in range(3):
    ii=(i+1)%3
    if xs[i]==xs[ii]:
        if xc>xs:
            include = (X > xs[i])
        else:
            include = (X < xs[i])
    else:
        slope=(ys[ii]-ys[i])/(xs[ii]-xs[i])
        poly=np.poly1d([slope,ys[i]-xs[i]*slope])

        if yc>poly(xc):
            include = (Y > poly(X))
        else:
            include = (Y < poly(X))
    triangle*=include

答案 2 :(得分:0)

from operator import abs
def renj(pts):
    X=[]
    Y=[]
    for i in range(len(pts)):
        if i in [0,2,4]:                    #(0-x1, 1-y1) (2-x2,3-y2) (4-x3,5-y3)
            X.append(pts[i])
        else:   
            Y.append(pts[i])
    return [min(X), max(X), min(Y), max(Y)]             # returns the range for triangle.

def m(a,b):
    from math import e
    if b[0]-a[0]:
            return (b[1]-a[1])/(b[0]-a[0])
    return e

def test(a,b,z):                                        # creating function to check if z lies on line(ab)
    if m(a,b)==m(a,z):
        return 1
    return 0    

n=int(input())      
for i in range(n):
    points = list(map(int, input().split()))
    count = 0
    A=[points[0], points[1]]
    B=[points[2], points[3]]
    C=[points[4], points[5]]
    r = renj(points)
    for u in range(r[0], r[1]+1):
        for v in range(r[2], r[3]+1):
            Z=[u, v]
            if test(A,B,Z) or test(A,C,Z) or test(B, C, Z):
                count += 1
    aa=abs((A[0]*(B[1]-C[1])+B[0]*(C[1]-A[1])+C[0]*(A[1]-B[1]))/2)
    #print("are",aa)
    bb=count
    #print("b",bb)
    ii=(aa+1)-bb/2
    print(int(ii))