本文主要是介绍Python 二叉树算法解决二维装箱问题 (2d bin-packing problem),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
二维装箱问题应用领域比较多,游戏开发中主要应用于贴图合并。
最近在调研图集打包工具的算法实现,看到一种实现方式是通过二叉树算法,比较朴素且有效,则立刻写用例简单测试验证下。
测试结果:(打包后的图用随机纯色色块代替)
测试代码如下:
from Packer import Packer
from PIL import Image
import cv2
import os
import randomCanvas_Width = 1024
Canvas_Height = 1024
CanvasPixelColor = [255, 255, 255]
ImgPath = "imgLib"# 获取path下的所有图片对象
def getImgList(path):imagelist = []for parent, dirnames, filenames in os.walk(path):for filename in filenames:if filename.lower().endswith(('.png')):img = cv2.imread(os.path.join(parent, filename), cv2.IMREAD_UNCHANGED)imagelist.append(img)print(filename)return imagelist# 新建一张图
def newImg(width, height, r, g, b):img = Image.new('RGB', (width, height))for i in range(0, width):for j in range(0, height):img.putpixel((i, j), (r, g, b))img.save('sqr.png')return img# 在canvas上绘制纯色block
def drawBlockOnCanvas(canvasImg, x, y, w, h, r, g, b):for i in range(x, x + w):for j in range(y, y + h):canvasImg.putpixel((i, j), (r, g, b))return canvasImg# 新建画布
def drawCanvas():wallpaper = newImg(Canvas_Width, Canvas_Height, CanvasPixelColor[0], CanvasPixelColor[1], CanvasPixelColor[2])return wallpaper# 主函数
def main():# 新建一张 1024 * 1024 的画布canvas = drawCanvas()# 初始化Packer对象packer = Packer(Canvas_Width, Canvas_Height)# 读取图片sizeblocks = []rawImgList = getImgList(ImgPath)for img in rawImgList:print(img.shape)w, h, _ = img.shapeblocks.append({'w' : w, 'h' : h})# sort blocks by heightdef get_height(block):return block['h']blocks.sort(key = get_height, reverse=True)# 打包packer.fit(blocks)print("图的总数量" + str(len(blocks)))drawedCount = 0for block in blocks:print(str(block['w']) + "x" + str(block['h']))for block in blocks:print(str(block['w']) + "x" + str(block['h']))if('fit' in block):fit = block['fit']r = random.randint(0, 255)g = random.randint(0, 255)b = random.randint(0, 255)# print(block)drawBlockOnCanvas(canvas, fit['x'], fit['y'], block['w'], block['h'], r, g, b)drawedCount += 1## debug mode to show drew Img one by one# npImg = np.array(canvas)# cv2.imshow("test", npImg)# cv2.waitKey(0)# cv2.destroyAllWindows()else:print("[Error] No Fit in Block -- ")print("DrawedCount : " + str(drawedCount))canvas.save('sqr.png')canvas.show()main()
Packer类的实现:
class Packer:def __init__(self, w, h):self.root = {'x' : 0, 'y' : 0, 'w' : w, 'h' : h, 'used' : False}def fit(self, blocks):for block in blocks:node = self.findNode(self.root, block['w'], block['h'])if node:block['fit'] = self.splitNode(node, block['w'], block['h'])def findNode(self, root, w, h):if(root['used']):return self.findNode(root['right'], w, h) or self.findNode(root['down'], w, h)elif((w <= root['w']) and (h <= root['h'])):return rootelse:return Nonedef splitNode(self, node, w, h):node['used'] = Truenode['down'] = {'x' : node['x'], 'y' : node['y'] + h, 'w' : node['w'] , 'h' : node['h'] - h, 'used' : False}node['right'] = {'x' : node['x'] + w, 'y' : node['y'], 'w' : node['w'] - w, 'h' : h, 'used' : False}return node
测试验证结论:
算法不足之处在于block中的空白区域可能没有得到很好的利用,可以后续通过递归遍历blocks中"被浪费"的区域,将区域尽可能的合并后 重新利用。
这篇关于Python 二叉树算法解决二维装箱问题 (2d bin-packing problem)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!