只需使用python保留图像中的颜色范围区域

问题描述 投票:0回答:1

我在特定文件夹中有大量 JPG 图像,我只想在图像中保留

#c7d296
颜色,并用
white color
填充图像中的所有其他剩余区域。
为此,我无法使用 Photoshop,因为我有大量 JPG 图像,而且它占用了我很多时间! (关于
29000 JPG images
)。
为此,我应该在 python 脚本中使用
color range tool

我的图像类似于以下示例:
enter image description here

我为此过程编写了以下脚本:

import cv2
import os
import numpy as np
import keyboard

def keep_color_only(input_file, output_directory, color_range, fuzziness):
    try:
        # Read the input image
        img = cv2.imread(input_file)

        # Convert image to HSV color space
        hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

        # Define lower and upper bounds for the color range
        lower_color = np.array(color_range[0])
        upper_color = np.array(color_range[1])

        # Threshold the HSV image to get only desired colors
        mask = cv2.inRange(hsv, lower_color, upper_color)

        # Invert the mask
        mask_inv = cv2.bitwise_not(mask)

        # Create a white background image
        white_background = np.full_like(img, (255, 255, 255), dtype=np.uint8)

        # Combine the original image with the white background using the mask
        result = cv2.bitwise_and(img, img, mask=mask)
        result = cv2.bitwise_or(result, white_background, mask=mask_inv)

        # Output file path
        output_file = os.path.join(output_directory, os.path.basename(input_file))

        # Save the resulting image
        cv2.imwrite(output_file, result)

    except Exception as e:
        print(f"Error processing {input_file}: {str(e)}")

def process_images(input_directory, output_directory, color_range, fuzziness):
    # Create output directory if it doesn't exist
    if not os.path.exists(output_directory):
        os.makedirs(output_directory)

    # Process each JPG file in the input directory
    for filename in os.listdir(input_directory):
        if filename.lower().endswith('.jpg'):
            input_file = os.path.join(input_directory, filename)
            keep_color_only(input_file, output_directory, color_range, fuzziness)

            # Check for 'F7' key press to stop the process
            if keyboard.is_pressed('F7'):
                print("Process stopped by user.")
                return

def main():
    input_directory = r'E:\Desktop\inf\CROP'
    output_directory = r'E:\Desktop\inf\OUTPUT'

    # Color range in HSV format
    color_range = [(75, 90, 160), (95, 255, 255)]  # Lower and upper bounds for HSV color range
    fuzziness = 80

    process_images(input_directory, output_directory, color_range, fuzziness)
    print("Color removal completed.")

if __name__ == "__main__":
    main()

注意颜色范围的

fuzziness
必须设置为80
脚本运行良好,但整个输出图像由白色填充。这意味着输出图像只有一个空的白屏并且
no any #c7d296 color area keep

我的脚本问题出在哪里?

python opencv photoshop
1个回答
0
投票

看起来主要问题是如何使用蒙版将原始图像与白色背景组合起来。具体来说,您将蒙版应用到原始图像然后将其与白色背景组合的方式可能无法正确隔离所需的颜色。

这里有一个更简单的方法来解决这个问题:

  1. 确保遮罩正确隔离所需的颜色:通过创建所需颜色为白色而其他所有颜色均为黑色的二值图像,确保遮罩正确识别所需的颜色。

  2. 用白色填充其余部分:使用蒙版隔离所需的颜色后,用它用白色填充图像的其余部分。

确保顺序正确并更换您的代码。

来自

# Threshold the HSV image to get only desired colors
mask = cv2.inRange(hsv, lower_color, upper_color)

# Invert the mask
mask_inv = cv2.bitwise_not(mask)

# Create a white background image
white_background = np.full_like(img, (255, 255, 255), dtype=np.uint8)

# Threshold the HSV image to get only desired colors
mask = cv2.inRange(hsv, lower_color, upper_color)

# Create a white background image
white_background = np.full_like(img, (255, 255, 255), dtype=np.uint8)

# Combine the original image with the white background using the mask
# First, invert the mask to get the inverse mask
mask_inv = cv2.bitwise_not(mask)
© www.soinside.com 2019 - 2024. All rights reserved.