gitea_ap_art_assets/draw_outline.py

102 lines
3.2 KiB
Python

#!/usr/bin/python
#encoding:utf-8
import math
import cv2
import numpy as np
import os
from PIL import Image
import random
def generate_picture(name, high, wide):
"""生成图片"""
# 白色透明背景
img = np.ones((high, wide, 4)) * (255, 255, 255, 0)
# print("name", name)
# 保存为图片
#cv2.imwrite(name, img)
cv2.imencode('.png', img)[1].tofile(name)
def gen_outline(path, dest, offset):
img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
img_contour = cv2.imread(dest, cv2.IMREAD_UNCHANGED)
kernel_size = 1
sigma = 0.5
kernel = cv2.getGaussianKernel(kernel_size, sigma)
kernel = np.dot(kernel, kernel.T)
smoothed = cv2.filter2D(img, -1, kernel)
_, thresh = cv2.threshold(smoothed, 1, 255, cv2.THRESH_BINARY)
contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
# 计算轮廓的总面积
total_area = 0
for contour in contours:
area = cv2.contourArea(contour)
total_area = total_area + area
# 选择周长和面积满足条件的轮廓,过滤太小的轮廓
valid_contours = []
threshold = 0.5
idx = 0
while not (len(valid_contours) > 0 and idx == 0):
contour = contours[idx]
perimeter = cv2.arcLength(contour, True)
area = cv2.contourArea(contour)
# print(path, "周长 =", perimeter, "面积占比 =", area/total_area, threshold)
if perimeter > 0 and area/total_area > threshold:
# print("add =====> ")
valid_contours.append(contour)
idx = idx + 1
if idx >= len(contours):
threshold = threshold - 0.1
idx = 0
total = len(valid_contours[0])
start = random.randint(0, int(total/3*2))
# start = 0
end = start + int(total/3)
# end = total
contour_points = valid_contours[0][start:(end)]
pixle_offset = (int(offset / 2), int(offset / 2))
offset_contour_points = contour_points + pixle_offset
cv2.polylines(img_contour, [offset_contour_points], False, (255, 255, 255, 255), int(offset - 1), lineType=cv2.LINE_AA)
cv2.polylines(img_contour, [offset_contour_points], False, (0, 0, 0, 255), int(offset / 2 - 1), lineType=cv2.LINE_AA)
cv2.imwrite(dest, img_contour)
def draw_outline(path, offset, order):
img = cv2.imread(path)
h, w, c = img.shape
width = w + offset
height = h + offset
img_outline_path = path.replace(".png", "_outline.png")
generate_picture(img_outline_path, height, width)
gen_outline(path, img_outline_path, offset)
return img_outline_path
def paste(src, dest, x, y):
img2 = Image.open(dest)
img2 = img2.convert("RGBA")
img1 = Image.open(src)#小图路径
img1 = img1.convert("RGBA")
img2.paste(img1, (x, y), mask=img1)
img2.save(dest)
if __name__ == "__main__":
path = "/Users/mac/Documents/guru/unity_ap_bundle/ArtPuzzleBundle/Assets/Bundles/Levels/28/Atlas"
generate_picture("line_1.png", 1280, 1040)
os.system("cd {} && rm *_outline.png".format(path))
for root , dirs, files in os.walk(path):
for name in files:
if "patch_" in name and name.endswith(".png") and "outline" not in name:
# print("name = {}".format(name))
draw_outline(os.path.join(root, name), 3)