Image processing 使用opencv python删除背景

Image processing 使用opencv python删除背景,image-processing,Image Processing,有人能帮我用OpenCV Python删除背景吗?我正在尝试将其用于我的OCR项目 预期的示例图像为: 您可以尝试使用此示例代码删除背景 读取图像文件 转换为灰度 应用阈值 为了简单起见,我们采用了一个恒定的阈值 thresh = 127 im_b = cv2.threshold(img_gray, thresh, 255, cv2.THRESH_BINARY)[1] 找到图形的轮廓 对轮廓进行排序 基于轮廓的物体遮挡 根据您的示例图像,我的目标是根据轮廓区域裁剪出单个检测到的对象 我希

有人能帮我用OpenCV Python删除背景吗?我正在尝试将其用于我的OCR项目

预期的示例图像为:

您可以尝试使用此示例代码删除背景

读取图像文件 转换为灰度 应用阈值 为了简单起见,我们采用了一个恒定的阈值

thresh = 127   
im_b = cv2.threshold(img_gray, thresh, 255, cv2.THRESH_BINARY)[1]
找到图形的轮廓 对轮廓进行排序 基于轮廓的物体遮挡 根据您的示例图像,我的目标是根据轮廓区域裁剪出单个检测到的对象


我希望有帮助。干杯,伙计

您可以尝试使用此示例代码来删除背景

读取图像文件 转换为灰度 应用阈值 为了简单起见,我们采用了一个恒定的阈值

thresh = 127   
im_b = cv2.threshold(img_gray, thresh, 255, cv2.THRESH_BINARY)[1]
找到图形的轮廓 对轮廓进行排序 基于轮廓的物体遮挡 根据您的示例图像,我的目标是根据轮廓区域裁剪出单个检测到的对象


我希望有帮助。干杯,伙计

使用inRange函数选择:

import cv2 as cv
low_H = 0
low_S = 0
low_V = 220
high_H = 255
high_S = 30
high_V = 255
frame = cv.imread('EQsBj.jpg')
frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))
cv.imwrite('out_3.png', frame_threshold)
结果:

使用inRange功能选择:

import cv2 as cv
low_H = 0
low_S = 0
low_V = 220
high_H = 255
high_S = 30
high_V = 255
frame = cv.imread('EQsBj.jpg')
frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))
cv.imwrite('out_3.png', frame_threshold)
结果:

contours = sorted(contours, key = cv2.contourArea, reverse= True)
mask = np.ones(img.shape[:2], np.uint8)
mask.fill(255)
cv2.drawContours(mask, contours, contourIdx =0 , color =0, thickness = -1)
new_img = cv2.add(im_b, mask)
cv2.imwrite('masked.jpg',new_img)
cv2.imshow('masked.jpg')
import cv2 as cv
low_H = 0
low_S = 0
low_V = 220
high_H = 255
high_S = 30
high_V = 255
frame = cv.imread('EQsBj.jpg')
frame_HSV = cv.cvtColor(frame, cv.COLOR_BGR2HSV)
frame_threshold = cv.inRange(frame_HSV, (low_H, low_S, low_V), (high_H, high_S, high_V))
cv.imwrite('out_3.png', frame_threshold)