Python图像处理移动Imag

2024-10-02 06:31:45 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用python和PIL来操作两个图像。我使用getpixel和putpixel成功地将一个图像放置到另一个图像上。我们不允许使用pil提供的任何复制/粘贴功能(因此是getpixel和putpoixel)。现在我基本上尝试将第一个图像(比如说模板图像)放置到目标图像的用户定义位置。我知道如何接受用户输入,但是我不知道将这些变量放在哪里,使模板图像显示在用户的坐标上。我基本上想让这些坐标成为模板图像的新原点。我尝试使用坐标作为putpixel x和y,但我认为,这只是在用户的坐标上叠加像素。我肯定我错过了一些简单的东西。任何帮助都将不胜感激。顺便说一下,我使用的是python2.7。在

from PIL import Image
import sys

print "Image Manipulation\n"

tempImg = Image.open("template.png")
destImg = Image.open("destination.jpg")

tempWidth,tempHeight = tempImg.size
destWidth,destHeight = destImg.size

if tempWidth >= destWidth and tempHeight >= destHeight:
    print "Error! The template image is larger than the destination image."
    sys.exit()
else:
    print "The template image width and height: ",tempWidth,tempHeight
    print "The destination image width and height: ",destWidth,destHeight

x_loc = raw_input("Enter the X coordinate: ")
y_loc = raw_input("Enter the Y coordinate: ")

x_loc = int(x_loc) # <--where do I put these?
y_loc = int(y_loc)

tempImg = tempImg.convert("RGBA")
destImg = destImg.convert("RGBA")
img = tempImg.load()

for x in xrange(tempWidth):
    for y in xrange(tempHeight):
        if img[x,y][1] > img[x,y][0] + img[x,y][2]:
            img[x,y] = (255,255,255,0)
        else:
            destImg.putpixel((x,y),tempImg.getpixel((x,y)))


destImg.show()

Tags: 用户图像image模板imgtemplatelocprint
1条回答
网友
1楼 · 发布于 2024-10-02 06:31:45

我想出来了!在玩了很多变量之后,我找到了在哪里添加它们。我一直试图使用它们作为getpixel函数的x,y坐标,但我知道这基本上只会将它们叠加在一起,因为这些变量在循环中没有被更新。在

getpixel((x_loc,y_loc),...) #< wrong

然后它点击了:我只需要将用户的坐标添加到getpixel的x和y上。例如:

^{pr2}$

这基本上将模板图像的原点设置为用户的输入位置。我知道还有其他方法可以更快地完成这项工作,但是我们被要求只使用getpixel、putpoixel和open/saveimage。当然,这里我只是显示图像而不是保存它。请随意试用。在

print "Image Manipulation\n"
template = raw_input("Enter the template image: ")
destination = raw_input("Enter the destination image: ")

tempImg = Image.open(template)
destImg = Image.open(destination)

tempWidth,tempHeight = tempImg.size
destWidth,destHeight = destImg.size

if tempWidth >= destWidth and tempHeight >= destHeight:
    print "Error! The template image is larger than the destination image."
    sys.exit()
else:
    print "The template image width and height: ",tempWidth,tempHeight
    print "The destination image width and height: ",destWidth,destHeight

x_loc = raw_input("Enter the X coordinate: ")
y_loc = raw_input("Enter the Y coordinate: ")

x_loc = int(x_loc)
y_loc = int(y_loc)

tempImg = tempImg.convert("RGBA")
destImg = destImg.convert("RGBA")
img = tempImg.load()

for x in range(tempWidth):
    for y in range(tempHeight):
        if img[x,y][1] > img[x,y][0] + img[x,y][2]: #<  removes green border from image
            img[x,y] = (255,255,255,0)
        else:
            destImg.putpixel((x+x_loc,y+y_loc),tempImg.getpixel((x,y)))


destImg.show()

**注:此部分程序是可选的:

if img[x,y][1] > img[x,y][0] + img[x,y][2]:
        img[x,y] = (255,255,255,0)

我们得到的模板图片周围有一个绿色的边框,当我们把它放到目的地图片上时,我们被要求删除它。在

相关问题 更多 >

    热门问题