python实现:图片的像素处理(像素值查看,替换像素值,阈值处理)
【代码】python实现:替换图片中某个指定的像素值。
·
1. 像素值查看
from PIL import Image
import numpy as np
# 加载图像
image = Image.open('/home/****/pic.png')
# image = Image.open('output.png')
# 转换为NumPy数组
image_array = np.array(image)
# 获取不同的像素值和它们各自的数量
unique_pixels, counts = np.unique(image_array, return_counts=True)
# 将unique_pixels和counts按照像素值数量从大到小排序
sorted_indices = np.argsort(counts)[::-1]
unique_pixels = unique_pixels[sorted_indices]
counts = counts[sorted_indices]
# 打印像素值数量
print("图像中的不同像素值数量:", len(unique_pixels))
print("图像中的不同像素值:", unique_pixels)
# 打印结果
print("像素值最多的是:", unique_pixels[0])
print("出现次数:", counts[0])
print("像素值第二多的是:", unique_pixels[1])
print("出现次数:", counts[1])
2. 替换指定的像素值
import os
import numpy as np
from PIL import Image
from tqdm import tqdm
data_path = "/path/to/源图片根目录"
tgt_path = "/path/to/保存图片的根目录"
for _, _, files in os.walk(data_path):
for f in tqdm(files):
img = Image.open(os.path.join(data_path,f))
img = np.asarray(img).copy()
img[img == 1] = 255
img =Image.fromarray(img)
img.save(os.path.join(tgt_path, f))
3. 阈值处理
# import os
# from PIL import Image
# import numpy as np
#
# def change_pixel_values(input_folder, output_folder):
# if not os.path.exists(output_folder):
# os.makedirs(output_folder)
#
# file_list = os.listdir(input_folder)
#
# for file_name in file_list:
# input_path = os.path.join(input_folder, file_name)
# output_path = os.path.join(output_folder, file_name)
#
# image = Image.open(input_path).convert('L')
# pixel_array = np.array(image)
#
# pixel_array[pixel_array >= 20] = 255
#
# modified_image = Image.fromarray(pixel_array)
# modified_image.save(output_path)
#
# print("Pixel values changed and images saved!")
#
# # 调用示例
# input_folder = '/home/***/IDRiD'
# output_folder = '/home/***/TH_process'
#
# change_pixel_values(input_folder, output_folder)
from PIL import Image
import numpy as np
def change_pixel_values(image_path):
image = Image.open(image_path).convert('L') # 转换为灰度图像
pixel_array = np.array(image)
# 将非零像素值设置为255
pixel_array[pixel_array >= 10] = 255
modified_image = Image.fromarray(pixel_array)
return modified_image
image_path = '/home/***/pic.png'
modified_image = change_pixel_values(image_path)
modified_image.save('modified_pic.png')
更多推荐
已为社区贡献7条内容
所有评论(0)