如何使用PIL将矩形图像映射到四边形? [英] How to map rectangle image to quadrilateral with PIL?

查看:59
本文介绍了如何使用PIL将矩形图像映射到四边形?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python PIL库允许我使用

Python PIL library allows me to map any quadrilateral in an image to rectangle using

im.transform(size, QUAD, data)

我需要的是一个相反的功能,即将矩形图像映射到指定的四边形.

What I need is a function that does the opposite, i.e. map a rectangular image to specified quadrilateral.

我认为这可以通过上述功能来实现:

I figured this might be achieved with the above mentioned function like this:

即我会找到这样的四边形(图像中的红色),可以使用函数im.transform(size,QUAD,data)将图像转换为我想要的四边形.问题是我不知道如何找到红色四边形.

I.e. I would find such quad (the red one in the image) that would, using the function im.transform(size, QUAD, data) transform the image to quad I want. The problem is I don't know how to find the red quad.

对于任何关于如何找到红色四边形的想法,或任何其他将rect图像映射到四边形的方法,我将不胜感激.

I would appreciate any idea on how to find the red quad or any other way to map a rect image to quad, only with PIL if possible.

推荐答案

因此,我通过简单的前向映射而不是逆向映射解决了这个问题,通常情况下,逆向映射会更好,但是在我的应用程序中,我只将矩形映射到小于矩形的四边形,因此变换后的图像中通常没有孔.代码如下:

So I solved the issue with a simple forward mapping, rather than inverse mapping, which is usually better, but in my application I only ever map the rectangle to a quad that is smaller than the rectangle, so there are usually no holes in the transformed image. The code is as follows:

def reverse_quad_transform(image, quad_to_map_to, alpha):
  # forward mapping, for simplicity

  result = Image.new("RGBA",image.size)
  result_pixels = result.load()

  width, height = result.size

  for y in range(height):
    for x in range(width):
      result_pixels[x,y] = (0,0,0,0)

  p1 = (quad_to_map_to[0],quad_to_map_to[1])
  p2 = (quad_to_map_to[2],quad_to_map_to[3])
  p3 = (quad_to_map_to[4],quad_to_map_to[5])
  p4 = (quad_to_map_to[6],quad_to_map_to[7])

  p1_p2_vec = (p2[0] - p1[0],p2[1] - p1[1])
  p4_p3_vec = (p3[0] - p4[0],p3[1] - p4[1])

  for y in range(height):
    for x in range(width):
      pixel = image.getpixel((x,y))

      y_percentage = y / float(height)
      x_percentage = x / float(width)

      # interpolate vertically
      pa = (p1[0] + p1_p2_vec[0] * y_percentage, p1[1] + p1_p2_vec[1] * y_percentage) 
      pb = (p4[0] + p4_p3_vec[0] * y_percentage, p4[1] + p4_p3_vec[1] * y_percentage)

      pa_to_pb_vec = (pb[0] - pa[0],pb[1] - pa[1])

      # interpolate horizontally
      p = (pa[0] + pa_to_pb_vec[0] * x_percentage, pa[1] + pa_to_pb_vec[1] * x_percentage)

      try:
        result_pixels[p[0],p[1]] = (pixel[0],pixel[1],pixel[2],min(int(alpha * 255),pixel[3]))
      except Exception:
        pass

  return result

这篇关于如何使用PIL将矩形图像映射到四边形?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆