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()