捕获像素并创建新图像

时间:2016-04-08 04:23:34

标签: python image multidimensional-array jython pixel

我正在努力捕捉"图像区域中的所有像素(由在显示器上绘制的矩形对象的宽度和高度确定的区域),并创建包含从原始图像捕获的像素的新图像。

问题在于,当我运行它时,我的索引超出范围/坐标超出范围错误。我尝试打印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)

1 个答案:

答案 0 :(得分: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")