将显著性检测图像后处理,绘出一个矩形框,方便使用
先通过边缘检测,然后通过opencv接口实现
结果如下:
# --coding:utf
# -8-*-
import os
import cv2 as cv
import numpy as np
# canny边缘检测
def canny_demo(image):
t = 50
canny_output = cv.Canny(image, t, 95)
return canny_output
def image_target_detection(img, mask):
# 读取图像
src = cv.imread(mask)
img = cv.imread(img)
binary = canny_demo(src)
k = np.ones((5, 5), dtype=np.uint8)
binary = cv.morphologyEx(binary, cv.MORPH_DILATE, k)
# kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
# binary = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
cv.namedWindow("input", cv.WINDOW_NORMAL | cv.WINDOW_KEEPRATIO)
cv.resizeWindow("input", 400, 300)
cv.imshow("input", binary)
image, contours, hierarchy = cv.findContours(binary, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
print("contours", contours)
print("contours", len(contours))
print("contours", type(contours))
for c in range(len(contours)):
x, y, w, h = cv.boundingRect(contours[c])
cv.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 10)
rect = cv.minAreaRect(contours[c]) # 最小旋转矩形
cx, cy = rect[0]
box = cv.boxPoints(rect) # 点集的最小外接矩形
box = np.int0(box)
cv.drawContours(src, [box], 0, (0, 0, 255), 10)
cv.drawContours(img, [box], 0, (0, 0, 255), 10)
cv.circle(src, (np.int32(cx), np.int32(cy)), 2, (255, 0, 0), 2, 8, 0)
cv.drawContours(src, contours, c, (0, 0, 255), 2, 8)
# 图像显示
cv.namedWindow("contours_analysis", 0)
cv.resizeWindow("contours_analysis", 400, 300)
cv.imshow("contours_analysis", img)
# cv.namedWindow("out", 0)
# cv.resizeWindow("out", 400, 300)
# cv.imshow("out", src)
# cv.imwrite("D:/vsprojects/images/contours_analysis.png", src)
cv.waitKey(0)
cv.destroyAllWindows()
if __name__ == '__main__':
imgdir = 'E:\\data\\'
maskdir = 'E:\\data\\'
img_list = [imgdir + f for f in os.listdir(imgdir) if f.endswith("jpg")]
for img in img_list:
mask = maskdir + img.split(os.sep)[-1].split('.')[0] + '.png'
image_target_detection(img, mask)