我想分割尺寸为 128x 的图像?分成多个 128x128 部分,最后一部分的大小调整为高度 128。我希望第一个输出图像来自输入图像的底部。
我用了
convert -gravity south -crop 128x128 +repage untitled.png cropped_%d.png
不幸的是,重力选项被忽略。 cropped_0.png 是顶部部分。此外,我不知道如何调整最后一张图像的大小。
编辑:以下内容最后使cropped_0.png从底部开始,但没有cropped_1.png。
convert untitled.png -gravity South +repage -crop 128x128+0+0 +repage cropped_%d.png
答案1
现在使用这个:
#!/usr/bin/python3.9
import numpy as np
import cv2
import sys
import os
import math
import argparse
parser = argparse.ArgumentParser(description="split png image vertically from bottom")
parser.add_argument("fname", help="img file name")
parser.add_argument("prefix", help="prefix of output pngs")
parser.add_argument('--height', action='store_true', help="output img height. default 128")
parser.add_argument('--width', action='store_true', help="output img width. default 128")
args = parser.parse_args()
print(args.height)
print(args.fname)
abspath=os.path.abspath(args.fname)
absdir=os.path.dirname(abspath)
tarW = 128
if(args.width):
tarW = args.width
tarH = 128
if(args.height):
tarH = args.height
print(tarH)
img = cv2.imread(abspath, cv2.IMREAD_UNCHANGED)
if(img is not None):
height=img.shape[0]
width=img.shape[1]
fulls=math.floor(height/tarH)
total=math.ceil(height/tarH)
print("fulls:" + str(fulls))
print("total:" + str(total))
for i in range(0,fulls):
ty=height-((i+1)*tarH)
tx=0
by=ty+tarH
bx=tarW
iname = args.prefix + "_" + str(i) + ".png"
print(iname + ": cropping from " + str(tx) + "x" + str(ty) + " to " + str(bx) + "x" + str(by))
oimg=img[ty:by,tx:bx]
cv2.imshow("asd", oimg)
cv2.waitKey()
cv2.imwrite(absdir + "/" + iname, oimg)
#top rest
lty = 0
lby = height%tarH
ltx = 0
lbx = tarW
limg1=img[lty:lby,ltx:lbx]
iname = args.prefix + "_" + str(fulls) + ".png"
ydiff = tarH - lby
print(iname + ": cropping from " + str(ltx) + "x" + str(lty) + " to " + str(lbx) + "x" + str(lby) + ", missing " + str(ydiff) + "x" + str(tarW) + ". generating...")
#additional transparent
aw, ah = tarW, ydiff
n_channels = 4
transparent_top = np.zeros((ah, aw, n_channels), dtype=np.uint8)
oimg = cv2.vconcat([transparent_top, limg1])
cv2.imshow("asd", oimg)
cv2.waitKey()
cv2.imwrite(absdir + "/" + iname, oimg)
else:
print("not valid image")
sys.exit(1)