Skip to main content
 首页 » 编程设计

python之缩放图片的一部分

2025年05月04日12kerrycode

我想放大图片的一部分,在本例中是 Nose 。

我有一个功能,可以选择图片中我想放大的部分。

def copyAndPaste(picture): 
  height = getHeight(picture) 
  width = getWidth(picture) 
  newPicture = makeEmptyPicture(width, height) 
  for x in range(width): 
    for y in range(height): 
      pxl = getPixel(picture,x,y) 
      if (x>48 and x<59) and (y>58 and y<71): 
        newPxl =getPixel(newPicture, #?,#?) 
      else: 
        newPxl = getPixel(newPicture, x,y) 
      color = getColor(pxl) 
      setColor(newPxl,color) 
 
  return newPicture 
 
def d():     
  f=pickAFile() 
  picture=makePicture(f)         
  newPicture = copyAndPaste(picture)         
  writePictureTo(newPicture, r"D:\FOLDER\0Pic4.jpg") 
  explore (newPicture) 

我还有放大图片的功能:

def Enlarge(picture): 
  height = getHeight(picture) 
  width = getWidth(picture) 
  newPicture = makeEmptyPicture(width*2, height*2) 
  x1=0 
  for x in range(0,width): 
    y1=0 
    for y in range(0,height): 
      pxl = getPixel(picture,x,y) 
      newPxl = getPixel(newPicture, x1,y1) 
      color = getColor(pxl) 
      setColor(newPxl,color) 
 
      y1=y1+2 
    x1=x1+2 
 
  return newPicture 

例如
来自:

收件人:

我尝试了很多东西,但无法弄清楚如何将两者结合起来放大图片的一部分,而保留图片的其余部分。

这就是生成的图片应该看起来的样子(虽然很荒谬),

我一直在小图像上练习,因为程序可能需要很长时间才能执行,在这个阶段处理大图像是不可行的,这意味着结果是粗略的,但至少会显示它是否有效。

请您参考如下方法:

我仍然不确定我是否理解您想要做什么,但我认为它是这样的:您想复制并粘贴 Nose ,而不是剪切和粘贴,并且您希望粘贴的副本以与第二个示例相同的特殊方式加倍。

所以,脸部中间会有一个 10x10 的 Nose ,右下角还有一个 20x20 的洗过的 Nose 。


首先,要复制和粘贴,您只需将像素复制到旧位置和新位置,而不仅仅是复制到新位置:

def copyAndPaste(picture): 
  height = getHeight(picture) 
  width = getWidth(picture) 
  newPicture = makeEmptyPicture(width+100, height+100) 
  for x in range(width): 
    for y in range(height): 
      pxl = getPixel(picture,x,y) 
      color = getColor(pxl) 
      if (x>48 and x<59) and (y>58 and y<71): 
        newPxl =getPixel(newPicture, x+100,y+100) 
        setColor(newPxl,color) 
      newPxl = getPixel(newPicture, x,y) 
      setColor(newPxl,color) 

现在,要放大新粘贴的副本,只需将偏移量加倍即可。换句话说,49,59 处的第一个像素变为 149,159,但 50,60 处的像素变为 151,161,而 51,61 处的像素变为 153,163,依此类推。

所以,你想要的是得到与 49,59 的距离,将其加倍,将其加回到 49,59,然后将其移动 100,100:

      if (x>48 and x<59) and (y>58 and y<71): 
        newPxl =getPixel(newPicture, (x-49)*2+49+100,(y-59)*2+59+100) 
        setColor(newPxl,color)