我正在尝试裁剪图像,因此图像有黑色,上面有一些项目,我想裁剪包含这些项目的黑色背景并删除其余部分,我尝试使用此代码但无法实现此目的,请帮助我这个
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()