0

I am trying to crop an image so the image has black colour with some items on it and I want to crop the black background containing those items and remove the rest , I tried with this code but could not achieve this, please help me with this

import sys
from PIL import Image, ImageFilter
from path import Path
imgPath = Path(sys.argv[1])
print imgPath, imgPath.basename()
img = Image.open(imgPath)
contourImg = img.filter(ImageFilter.CONTOUR)
binaryImg = contourImg.convert("1")
rows, cols = binaryImg.size

imgData = binaryImg.load()
edgeDataX = []
edgeDataY = []

print "Image size = (%d,%d)" % (rows, cols)

for x in xrange(rows):
    for y in xrange(cols):
        if imgData[x,y] == 255:
            edgeDataX.append(x)
            edgeDataY.append(y)

print "\nEdge Points of cropped image: "

print (max(edgeDataX), min(edgeDataY)), (max(edgeDataX), max(edgeDataY))
print "croppig image.."

croppedImg = img.crop((min(edgeDataX), min(edgeDataY), max(edgeDataX), max(edgeDataY)))
croppedImgPath = imgPath.dirname() / imgPath.namebase + "_cropped.jpg"
print "\nCropped Image saved at : " + croppedImgPath
croppedImg.save(croppedImgPath)

croppedImg.show()
cagatayodabasi
  • 762
  • 11
  • 34
  • 4
    You may elaborate the question and add sample input images and expected outputs as well. – ZdaR May 03 '17 at 07:10
  • I think this may be helpful http://stackoverflow.com/questions/40527769/removing-black-background-and-make-transparent-from-grabcut-output-in-python-ope – Pankaj Sharma May 03 '17 at 10:55

0 Answers0