一.效果图展示
原图:
提取后:
二.源码
import cv2 as cv
import numpy as np
import os
import shutil
def canny_demo(image):
t = 80
canny_output = cv.Canny(image, t, t * 2)
return canny_output
def GetRed(img):
"""
提取图中的红色部分
"""
# 转化为hsv空间
hsv = cv.cvtColor(img, cv.COLOR_BGR2HSV)
# print(hsv.shape)
# 颜色在HSV空间下的上下限
low_hsv = np.array([0, 180, 80])
high_hsv = np.array([10, 255, 255])
# 使用opencv的inRange函数提取颜色
mask = cv.inRange(hsv, lowerb=low_hsv, upperb=high_hsv)
Red = cv.bitwise_and(img, img, mask=mask)
return Red
def get_roi(base_path):
for filename in os.listdir(base_path):
src_path = os.path.join(base_path, filename)
img = cv.imread(src_path)
src = GetRed(img)
binary = canny_demo(src)
k = np.ones((3, 3), dtype=np.uint8)
binary = cv.morphologyEx(binary, cv.MORPH_DILATE, k)
contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
for c in range(len(contours)):
area = cv.contourArea(contours[c])
arclen = cv.arcLength(contours[c], True)
if area < 100 or arclen < 100:
continue
rect = cv.minAreaRect(contours[c])
cx, cy = rect[0]
box = cv.boxPoints(rect)
box = np.int0(box)
listX = [box[0][0], box[1][0], box[2][0], box[3][0]]
listY = [box[0][1], box[1][1], box[2][1], box[3][1]]
x1 = min(listX)
y1 = min(listY)
x2 = max(listX)
y2 = max(listY)
# print(x1, y1, x2, y2)
width = np.int32(x2 - x1)
height = np.int32(y2 - y1)
roi = img[y1 + 5: y2 - 5, x1 + 5:x2 - 5]
# print(width, height)
# print(x1,y1,x2,y2)
if width < 80 or height < 80:
continue
cv.imshow("roi", roi)
cv.waitKey(0)
cv.destroyAllWindows()
#根目录,可批量处理多张图片
base_path = r"F:\test"
get_roi(base_path)