SciTech-Mathmatics-ImageProcessing-Remove the Background Color or Image from an image using Python+NumPy+Pandas

https://www.geeksforgeeks.org/how-to-remove-the-background-from-an-image-using-python/

Remove Background Image

# Install required packages first.
# pip install Pillow
# pip install rembg
from rembg import remove 
from PIL import Image 
  
input_path =  './RemoveBackGroundOriginal.png' 
output_path = './Remove BackGroundOutput.png' 
input = Image.open(input_path) 
remove(input).save(output_path)

Remove Background Color

当背景颜色与图片主体部分的颜色有一定的区分度时,
就可以用这种办法把整片整片的背景颜色都替换成我们需要的颜色值。
我们直接就能用数值分析算法, 统计概率, 并以NumPy和Pandas实现数值统计。

# Usage: ipython --pdb removeColor.py 18
#! /usr/bin/env python
import itertools as it
import collections as ct
import cv2 as cv
import numpy as np
import pandas as pd


def calculate_top_color(image):
   a = image.copy()
   cnt = ct.Counter(a)
   topTen = cnt.most_common(10)
   topTenColors=[k for k,v in topTen]
   topColor=np.array(topTenColors).mean()
   return topColor

def replace_color(image, top=None, threshold=5, color=255):
   color_threshold = threshold
   a = image.copy()
   s = pd.Series(image.flatten())
   rows, cols = image.shape
   topColor0 = top or calculate_top_color(s)
   topColor = top or int(s.describe()['50%'])
   colorMin = topColor - color_threshold
   colorMax = topColor + color_threshold
   print(s.describe(), '\n', "TopColor: %s, %s\n" % (topColor, topColor0))
   for r in range(rows):
      for c in range(cols):
         val = a.item(r, c)
         if  colorMin <= val < colorMax:
            a.itemset((r, c), color)
   return a

def remove_top_color(img, top=None, threshold=18, color=255):
   b, g, r =img[:, :, 0], img[:, :, 1], img[:, :, 2]
   print("\nProcessing Color Channel: BLUE")
   b = replace_color(b, top, threshold, color)

   print("\nProcessing Color Channel: GREEN")
   g = replace_color(g, top, threshold, color)

   print("\nProcessing Color Channel: RED")
   r = replace_color(r, top, threshold, color)
   img0 = cv.merge((b, g, r))
   return img0


if __name__ == "__main__":
   import os,sys
   threshold = int(sys.argv[1]) if len(sys.argv) > 1 else 18
   # Load the image first
   img_path = './Signature.jpg'
   img0 = cv.imread(img_path)
   assert img0 is not None, "file could not be read, check with os.path.exists('%s')" % img_path

   cv.imwrite('Original.jpg', img0)
   img1 = remove_top_color(img0, threshold=threshold)
   cv.imwrite('Output.jpg', img1)
posted @ 2024-08-05 19:12  abaelhe  阅读(27)  评论(0)    收藏  举报