if __name__ == '__main__': num = 0 while num < 2: count = 0 while count < 2: print_row() print_col() if count == 1: print_row() count = count + 1 if num < 1: print_par() num = num+1
defprint_out(message, point, num, cap): #这四个参数分别对应输入字符串,标点类型,标点个数,大小写 message += point * num #将标点加入句末 if cap: #这里的cap是布尔类型,True返回小写,False返回大写 return message return message.upper()
# 将 NxM 图像调整为所需的高度和宽度。 # 注意:此功能只会使图像变小。 放大图像未实现。 # 输入:图像,一个大小为 NxMx3 的 3d numpy 数组 # desired_width,一个给出所需宽度的整数 # desired_height,一个给出所需高度的整数 # 输出:调整后的图像,现在大小为 N x desired_width x 3 defseam_carve(image, desired_height, desired_width): while image.shape[1] > desired_width: seam = find_vertical_seam(energy(image)) assertlen(seam) == image.shape[0], "the length of the seam must equal the height of the image" image = remove_vertical_seam(image, seam) sys.stdout.write('\rWidth is now %d' % image.shape[1]) print() while image.shape[0] > desired_height: seam = find_horizontal_seam(energy(image)) assertlen(seam) == image.shape[1], "the length of the seam must equal the width of the image" image = remove_horizontal_seam(image, seam) sys.stdout.write('\rHeight is now %d' % image.shape[0]) print() return image
deffind_vertical_seam(energy): N, M = energy.shape # 初始化优化问题,给它起个名字 prob = pulp.LpProblem("Seam carving", pulp.LpMinimize) # 创建变量 x = pulp.LpVariable.dicts("pixels",(list(range(N)),list(range(M))),0,1,pulp.LpInteger) # 构建目标函数 objective_terms = list() for i inrange(N): for j inrange(M): objective_terms.append(energy[i][j] * x[i][j]) prob += pulp.lpSum(objective_terms) # adds up all the terms in the list # Constraint #1: 每行一个像素 for i inrange(N): prob += pulp.lpSum(x[i][j] for j inrange(M)) == 1 # Constraint #2: 接缝的连通性 for i inrange(N-1): for j inrange(M): prob += pulp.lpSum([x[i][j]]+[-x[i+1][k] for k inrange(max(0,j-1),min(M,j+2))]) <= 0 prob.solve() # 通过收集最佳接缝中的像素来构建接缝 # 可以使用 pulp.value(x[i][j]) 访问变量的值(0 或 1) seam = [] for i inrange(N): for j inrange(M): if pulp.value(x[i][j]) == 1.0: seam.append(j) return seam
再次测试
1 2 3 4 5 6 7 8 9 10 11 12
# 重复上述测试,可以看到线性规划比纯递归快了很多 np.random.seed(1) h = 31 w = 31 img = np.random.randint(0,255,(h,w,3)).astype("uint8") print(img.shape) plt.figure() plt.imshow(img) e = energy(img) img3 = seam_carve(img, h, w-1) plt.figure() plt.imshow(img3)