【问题标题】:Capture pixels and create new image捕获像素并创建新图像
【发布时间】:2025-12-03 01:35:01
【问题描述】:

我正在尝试“捕获”图像区域(由在显示器上绘制的矩形对象的宽度和高度确定的区域)中的所有像素,并创建一个包含从原始图像。

问题是当我运行它时,我得到索引超出范围/坐标超出范围错误。我尝试打印 chord_pixels 数组的长度(以获取行数,应与矩形的宽度相同)和 chord_pixels[0] 的长度(以获取列数,应相同作为矩形的高度),事实证明,这些通常与新图像的高度和宽度(与像素来自的矩形大小相同)非常不同。差异通常超过 100。我已经研究了几个小时,并尝试了很多想法,包括非常愚蠢的想法。现在我把它提供给互联网。

img = Icon("name")
d = Display("name", 1000, 1000)
img.setSize(1000,1000)
d.add(img)

beginX,beginY,endX,endY = 0,0,0,0
chord_pixels = []
rect = Rectangle(0,0,0,0)

def beginRectangle(x,y):
   global beginX, beginY
   ...
   beginX, beginY = x, y

def drawRectangle(x,y):
   global beginX, beginY, endX, endY, rect
   ...
   if rect in d.getItems():
      d.remove(rect)     
   endX, endY = x,y
   rect = Rectangle(beginX, beginY, endX, endY, Color.BLACK, False, thickness=3)
   d.add(rect)    

def endRectangle(x,y):
   global beginX, beginY, endX, endY, img 
   ... 
   getPixelsInRectangle(img, beginX, beginY, endX, endY)

def getPixelsInRectangle(image, x1, y1, x2, y2):
   global chord_pixels
   row_pixels = []
   chord_pixels = []
   for y in range(y1,y2):        
      for x in range(x1, x2):    
         pixel = img.getPixel(int(y),int(x)) #getPixel(col, row)
         row_pixels.append(pixel) 
      chord_pixels.append(row_pixels)
      row_pixels = []

def captureChordPixels(key):
   global chord_pixels, rect
   chordWindow = Image(rect.getWidth(), rect.getHeight())
   for col in range(chordWindow.getHeight()):
      for row in range(chordWindow.getWidth()):
         chordWindow.setPixel(col, row, chord_pixels[col][row])

d.onMouseDown(beginRectangle)
d.onMouseDrag(drawRectangle)
d.onMouseUp(endRectangle)
d.onKeyDown(captureChordPixels)

【问题讨论】:

  • 明确地说,您要做的就是从给定子图像的 x,y,w,h 的原始图像中获取子图像?

标签: python image multidimensional-array jython pixel


【解决方案1】:

如果你对使用 PIL 没问题,那就很容易了。

crop() 接受定义左、上、右和下像素坐标的 4 项元组。 (x1,y1,x2,y2)

im = Image.open("image.png")
x1 = 0
y1 = 0
x2 = 500
y2 = 100
croppedImg = im.crop((x1,y1,x2,y2))
croppedImg.save("new-img.png")

【讨论】:

  • 哇。我觉得我浪费了很多时间。 (因为我真的做到了)。谢谢!
最近更新 更多