3

我正在尝试编写一个 python 函数,它将一个三角形区域从图片上的任何地方复制到一个新的空白图片。我可以将图片中的矩形区域复制到新的空白图片中,但我只是不知道如何复制三角形。这就是我所拥有的,但它只复制一个矩形区域。抱歉,如果它看起来凌乱或过于复杂,但我刚刚开始如何用 python 编写。

  def copyTriangle():
     file=pickAFile()
     oldPic=makePicture(file)
     newPic=makeEmptyPicture(getWidth(oldPic),getHeight(oldPic))
     xstart=getWidth(oldPic)/2
     ystart=getHeight(oldPic)/2
     for y in range(ystart,getHeight(oldPic)):
         for x in range(xstart,getWidth(oldPic)):
           oldPixel=getPixel(oldPic,x,y)
           colour=getColor(oldPixel)
           newPixel=getPixel(newPic,x,y)
           setColor(newPixel,colour)
4

2 回答 2

5

将三角形区域从一张照片复制到另一张照片的功能。

def selectTriangle(pic):
  w= getWidth (pic)
  h = getHeight(pic)
  newPic = makeEmptyPicture(w,h)
  x0=107#test point 0
  y0=44
  x1=52#test point 1
  y1=177
  x2=273 #test point 2
  y2=216
#(y-y0)/(y1-y0)=(x-x0)/(x1-x0)

  for y in range (0,h):
    for x in range (0, w):
#finding pixels within the plotted lines between eat set of points
      if (x>((y-y0)*(x1-x0)/(y1-y0)+x0) and x<((y-y0)*(x2-x0)/(y2-y0)+x0) and x>((y-y2)*(x1-x2)/(y1-y2)+x2)): 
        pxl = getPixel(pic, x, y)
        newPxl= getPixel(newPic,x,y)
        color = getColor(pxl)
        setColor (newPxl, color)

  return (newPic)

原始图像 三角形

于 2013-07-10T17:49:31.083 回答
2

如果您愿意像示例中那样逐个像素地进行操作,则只需复制三角形的像素即可。大多数情况下,这取决于您要如何定义三角形。

最简单的三角形是使您的 x 范围(内循环)取决于您的 y 值(外循环),例如:

for y in range(ystart, ystart+getHeight(oldPic)):
    for x in range(xstart, xstart + int( getWidth(oldPic)*((y-ystart)/float(getHeight)):

更一般地说,您仍然可以保留相同的 x 和 y 循环,然后将复制命令放在一个if块中,在那里您检查该点是否在您的三角形中。

除此之外,还有更有效的方法可以做到这一点,例如使用掩码等。

请注意,在这里我也将 y 范围更改为range(ystart, ystart+getHeight(oldPic)),我认为这可能是您想要的高度不依赖于起始位置。

于 2013-01-13T03:46:36.593 回答