如何用Python将分层TIFF转为PSD以在Photoshop中正常显示图层?
解决方案
方案1:直接生成PSD文件(替代分层TIFF)
原代码生成的分层TIFF在Photoshop中存在兼容性问题,可直接修改代码将图层保存为PSD格式。Pillow 9.1.0及以上版本支持多图层PSD的保存,能确保Photoshop正常识别所有分层内容。
修改后的完整代码:
import cv2 import numpy as np import os from sklearn.cluster import KMeans from PIL import Image # Load the image using OpenCV image = cv2.imread("Testing_samples/test5.jpg", cv2.IMREAD_COLOR) # Convert BGR to RGB image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # Reshape the array for clustering x = image_rgb.reshape(-1, 3) # Apply KMeans clustering kmeans = KMeans(n_clusters=4).fit(x) segmented_image = kmeans.cluster_centers_[kmeans.labels_] segmented_image = segmented_image.reshape(image_rgb.shape) num_clusters = 4 # Create a directory to save the PSD file psd_dir = "Testing_PSD" os.makedirs(psd_dir, exist_ok=True) # Create an empty list to store segmented layer images layer_images = [] # Plot each segmented color cluster for i in range(1, num_clusters + 1): boolean_index = kmeans.labels_ == (i - 1) if boolean_index.sum() > 0: segmented_layer = np.zeros_like(image, dtype=np.uint8) mask = np.zeros(image.shape[:2], dtype=bool) mask.flat[boolean_index] = True for channel in range(image.shape[-1]): segmented_layer[:, :, channel][mask] = kmeans.cluster_centers_[i - 1][channel] # Add transparency channel alpha_channel = np.zeros_like(image[:, :, 0], dtype=np.uint8) alpha_channel[mask] = 255 # Set pixels in the segment to fully opaque segmented_layer = np.dstack([segmented_layer, alpha_channel]) # Convert the segmented layer to a PIL Image pil_layer = Image.fromarray(segmented_layer, 'RGBA') # Append the segmented layer image to the list layer_images.append(pil_layer) # Save the list of layer images as a single PSD file layered_psd_path = os.path.join(psd_dir, "test_4_16_layers.psd") layer_images[0].save(layered_psd_path, save_all=True, append_images=layer_images[1:], format="PSD") print(f"Segmented layers PSD file saved: {layered_psd_path}")
方案2:将已有的分层TIFF转换为PSD
如果已经生成了分层TIFF文件,可通过以下代码读取所有图层并转换为PSD格式:
from PIL import Image import os def tiff_to_psd(tiff_path, output_psd_path): # 打开分层TIFF文件 with Image.open(tiff_path) as img: layers = [] # 遍历所有图层 try: while True: # 复制当前图层 layer = img.copy() layers.append(layer) # 跳转到下一个图层 img.seek(img.tell() + 1) except EOFError: # 遍历完所有图层,退出循环 pass # 保存为PSD文件 if layers: layers[0].save(output_psd_path, save_all=True, append_images=layers[1:], format="PSD") print(f"PSD file saved: {output_psd_path}") else: print("No layers found in the TIFF file.") # 示例调用 tiff_dir = "Testing_Tiff" tiff_path = os.path.join(tiff_dir, "test_4_16_layers.tiff") psd_dir = "Testing_PSD" os.makedirs(psd_dir, exist_ok=True) output_psd_path = os.path.join(psd_dir, "converted_from_tiff.psd") tiff_to_psd(tiff_path, output_psd_path)
注意事项
- 确保安装Pillow 9.1.0或更高版本,可通过
pip install --upgrade pillow升级 - PSD格式保存时,图层的透明通道会被正确保留,Photoshop可正常识别所有分层内容
内容的提问来源于stack exchange,提问作者Istiyak Shaikh
相关产品推荐
相关产品推荐

