png图片转换tif图片格式(只有目标和背景两种颜色)

在这里以红色目标为例子,我的背景里面有很多颜色,但是我只想要红色的目标部分
(注:这里的程序是将图片中的红色目标提取出来,其余背景全是黑色,如果想要其他颜色,请根据阈值自行修改)

首先运行下面程序,将图片中的目标提取出来

from PIL import Image
import numpy as np


def extract_red_channel(input_path, output_path):
    # Load the image
    image = Image.open(input_path)

    # Convert image to RGBA (in case it's not)
    image = image.convert("RGBA")

    # Split the image into channels
    red_channel, green_channel, blue_channel, alpha_channel = image.split()

    # Create a new image with red channel and alpha channel
    # The numpy array is used to create a mask where the red channel is dominant
    red_data = np.array(red_channel)
    green_data = np.array(green_channel)
    blue_data = np.array(blue_channel)

    # Define the threshold for red (values may need to be adjusted)
    red_threshold = 100
    green_threshold = 50
    blue_threshold = 50

    # Create a mask where only the red pixels are kept
    mask = (red_data > red_threshold) & (green_data < green_threshold) & (blue_data < blue_threshold)

    # Apply the mask to the alpha channel to set non-red pixels to transparent
    alpha_data = np.array(alpha_channel)
    alpha_data[~mask] = 0  # Set alpha to zero where mask is False

    # Convert the numpy array back to an image
    new_alpha_channel = Image.fromarray(alpha_data, 'L')

    # Merge the red channel and new alpha channel back into an image
    red_image = Image.merge("RGBA", (red_channel, green_channel, blue_channel, new_alpha_channel))

    # Save the image
    red_image.save(output_path)


# Define the input and output paths
input_path = 'example.png'  # Update this to the path of your source image
output_path = '2.png'  # Update this to your desired output path

# Call the function to extract the red channel
extract_red_channel(input_path, output_path)

print(f"Extracted red channel image saved to {output_path}")

然后在运行下面程序,将png图片转为tif图片格式:

from PIL import Image


# 定义一个函数来转换图片格式
def convert_png_to_tif(png_file_path, tif_file_path):
    # 使用Pillow库打开PNG图片
    png_image = Image.open(png_file_path)

    # 将图片保存为TIF格式
    png_image.save(tif_file_path, format='TIFF')


# 示例用法
# 假设有一个名为"example.png"的PNG图片,我们想将其转换为"converted.tif"
# 请替换这里的文件路径为你自己的文件路径
png_file_path = 'red.png'
tif_file_path = '1.tif'

# 调用函数进行转换
convert_png_to_tif(png_file_path, tif_file_path)

# 打印完成信息
print("图片转换完成。")

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值