侧边栏壁纸
  • 累计撰写 18 篇文章
  • 累计创建 25 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

8.单色背景剔除

遗失的记忆
2024-09-25 / 0 评论 / 0 点赞 / 17 阅读 / 2776 字

对背景为单色的图片进行替换,方面后续进一步处理

纯黑色处理

import cv2
import numpy as np
pic_name = 'crop_pic.jpg'
img = cv2.imread(pic_name)

#生成黑色图片
one = np.ones(img.shape)  
one[:,:,:] = [45,35,30] # 某黑色的BGR
#颜色比对
tt = (img[:,:,0] <= one[:,:,0]) &(img[:,:,1] <= one[:,:,1]) &(img[:,:,2] <= one[:,:,2])
#替换颜色
new_img = np.stack((np.where( tt ,255, img[:,:,0] ), np.where( tt ,255, img[:,:,1] ), np.where( tt ,255, img[:,:,2] ) ), axis=2)
cv2.imwrite('replace_crop_pic.jpg', new_img)

crop_pic.jpg

crop_pic.jpg

replace_crop_pic.jpg

replace_crop_pic.jpg

范围内色彩处理

处理处于某个区间内的色彩:

import cv2
import numpy as np
from collections import defaultdict  
def find_most_point(img):
    element_counts = defaultdict(int)  
    for sublist in img:  
        for subsublist in sublist:  
            element_counts[tuple(subsublist)] += 1  # 将列表转换为元组作为字典的键  
    max_count = max(element_counts.values())  
    most_frequent = [k for k, v in element_counts.items() if v == max_count][0]  # 可能会有多个元素出现次数相同  
    most_frequent = list(most_frequent)  
    return most_frequent

pic_name = 'case.jpg'
img = cv2.imread(pic_name)

# 找到要替换的色彩区间
most_color = find_most_point(img) # 找出现最多的色彩
floor_color = np.array(most_color) - 25 # 下限
upper_color = np.array(most_color) + 25 # 上限

#生成同形状的比对图片
floor = np.ones(img.shape)  
upper = np.ones(img.shape)  
floor[:,:,:] = floor_color
upper[:,:,:] = upper_color

#筛选出符合条件的点,对所有点3色进行比较
tt1 = (img[:,:,0] <= upper[:,:,0]) &(img[:,:,1] <= upper[:,:,1]) &(img[:,:,2] <= upper[:,:,2])
tt2 = (img[:,:,0] >= floor[:,:,0]) &(img[:,:,1] >= floor[:,:,1]) &(img[:,:,2] >= floor[:,:,2])
tt = tt1 & tt2
#生成新的图片
new_img = np.stack((np.where( tt ,255, img[:,:,0] ), np.where( tt ,255, img[:,:,1] ), np.where( tt ,255, img[:,:,2] ) ), axis=2)
cv2.imwrite('new_case.jpg', new_img)

case.jpg

case.jpg

new_case.jpg

new_case.jpg

0

评论区