CentOS cv2去除背景后选择指定位置并保存图片
以下是一个示例代码,用于在CentOS上使用cv2库去除图像背景并选择指定位置并保存图像:
import cv2
# 读取图像
img = cv2.imread('input.jpg')
# 转换为灰度图像
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# 去除背景
bg = cv2.createBackgroundSubtractorMOG2()
fgmask = bg.apply(gray)
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 5))
fgmask = cv2.morphologyEx(fgmask, cv2.MORPH_OPEN, kernel)
# 找到轮廓
contours, hierarchy = cv2.findContours(fgmask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
for cnt in contours:
# 计算轮廓面积
area = cv2.contourArea(cnt)
if area < 1000:
continue
# 找到轮廓的边界框
x, y, w, h = cv2.boundingRect(cnt)
# 在原图像中绘制边界框
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
# 保存选定的图像
roi = img[y:y + h, x:x + w]
cv2.imwrite('output.jpg', roi)
此代码将读取名为“input.jpg”的图像,并使用cv2库去除其背景。然后,它将找到图像中的轮廓,并选择具有面积大于1000的轮廓。对于每个选定的轮廓,代码将在原始图像中绘制边界框,并将选定的图像保存到名为“output.jpg”的文件中
原文地址: https://www.cveoy.top/t/topic/hra2 著作权归作者所有。请勿转载和采集!