OpenCV中物体颜色/透明性导致边界检测及Feret测量异常求助
图像物体检测与测量:背景分离优化问题
我正在开展图像物体检测与测量项目,单张图像仅包含一个物体。当前采用OpenCV的背景减法移除背景,再通过feret库计算最大、最小Feret直径。但因物体颜色或透明性问题,背景减法无法精准检测物体边界,进而导致Feret直径测量结果不准确。
运行代码(Jupyter Notebook)
import cv2 as cv import os import numpy as np import matplotlib.pyplot as plt # Clean up plt.close('all') import os import numpy as np from PIL import Image from tqdm import tqdm import cv2 # Import OpenCV for image preprocessing import feret # Import the feret module # Function to display images in Jupyter def display_image(image, title='Image'): plt.figure(figsize=(10, 10)) plt.imshow(image, cmap='gray') plt.title(title) plt.axis('off') plt.show() # Path to the folder containing images and the background image image_folder = '.' background_image_path = 'Main.jpeg' # Load the background image background_image = cv.imread(background_image_path, cv.IMREAD_COLOR) if background_image is None: print(f"Unable to load background image: {background_image_path}") exit(1) # Convert background image to grayscale background_gray = cv.cvtColor(background_image, cv.COLOR_BGR2GRAY) # Iterate through each file in the folder for filename in os.listdir(image_folder): if filename.endswith('.jpeg') and filename != 'Main.jpeg': image_path = os.path.join(image_folder, filename) # Load the current image image = cv.imread(image_path, cv.IMREAD_COLOR) if image is None: print(f"Unable to load image: {image_path}") continue # Convert current image to grayscale image_gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY) # Perform background subtraction fgMask = cv.absdiff(background_gray, image_gray) # Apply a threshold to get the binary image _, fgMask = cv.threshold(fgMask, 50, 255, cv.THRESH_BINARY) # Display the original image and the foreground mask display_image(cv.cvtColor(image, cv.COLOR_BGR2RGB), title='Original Image') display_image(fgMask, title='Foreground Mask') # Plot Feret diameters on the preprocessed image feret.plot(fgMask) # Calculate Feret diameters and angles maxf_length, minf_length, minf_angle, maxf_angle = feret.all(fgMask) # Print the results for the current image print(f"Filename: {filename}, Max Feret Length: {maxf_length}, Min Feret Length: {minf_length}") # result_path = os.path.join('path_to_save_results', f'fgMask_{filename}') # cv.imwrite(result_path, fgMask) # Pause to control the display in the notebook # This can be adjusted or removed as needed input("Press Enter to continue...") # Clean up plt.close('all') # Optionally, print all results at the end # for res in results: # print(f"Filename: {res['filename']}, Max Feret Length: {res['maxf_length']}, Min Feret Length: {res['minf_length']}")
相关素材说明
- 背景图:白色底带蓝色网格的标准背景
- 样本图:多张包含透明/浅色不规则物体的图像
- 当前输出:背景分割后的掩码存在边界缺失、物体轮廓不完整的问题
提问
请问OpenCV中是否有替代方法或预处理步骤能更好地分离物体与背景?恳请相关建议与指导。
内容的提问来源于stack exchange,提问作者Agura
相关产品推荐
相关产品推荐

