这样的一张图片,用普通的等宽来切割:
def sliceImg(img, outDir, count = 4): w, h = img.size eachWidth = int(w / count) for i in range(count): box = (i * eachWidth, 0, (i + 1) * eachWidth, h) img.crop(box).save(outDir + str(i) + ".png")
可以看到切割效果很差,3都要切成8了。
我们可以换种思想,在目标位置的前后进行垂直上的像素判断,判断某一列的黑色像素最少,就是切割点。代码改成:
def smartSliceImg(img, outDir, count = 4, p_w = 3): ''' :param img: :param outDir: :param count: 图片中有多少个图片 :param p_w: 对切割地方多少像素内进行判断 :return: ''' w, h = img.size pixdata = img.load() eachWidth = int(w / count) beforeX = 0 for i in range(count): allBCount = [] nextXOri = (i + 1) * eachWidth for x in range(nextXOri - p_w, nextXOri + p_w): if x >= w: x = w - 1 if x < 0: x = 0 b_count = 0 for y in range(h): if pixdata[x, y] == 0: b_count += 1 allBCount.append({'x_pos': x, 'count':b_count}) sort = sorted(allBCount, key=lambda e: e.get('count')) nextX = sort[0]['x_pos'] box = (beforeX, 0, nextX, h) img.crop(box).save(outDir + str(i) + ".png") beforeX = nextX
可以看到切割效果好多了,但是这种还是无法处理斜着的情况。
3778