将这张图读取边框
读取图片
import cv2
import numpy as np
img_name = r"E:\new-learning\learn-porject\learn_opencv_tiqubiankuan_smarttrash\image\3.jpg"
img = cv2.imread(img_name)
new_size = (500, 600)
img = cv2.resize(img, new_size)
cv2.imshow('first', img)
# 等待用户按下任意键
cv2.waitKey(0)
# 关闭图像窗口
cv2.destroyAllWindows()
彩色图像灰度化
gray_img = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)
cv2.imshow('gray', gray_img)
# 等待用户按下任意键
cv2.waitKey(0)
# 关闭图像窗口
cv2.destroyAllWindows()
二值化,均值滤波,OTSU分割法,之后画边框
# _, binary_image = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
# threshold_value = img.mean()
# print(threshold_value)
cv2.imshow('gray', gray_img)
# 均值滤波
blurred_img = cv2.blur(gray_img, (5, 5)) # 可调整内核大小
cv2.imshow('blurred', blurred_img)
# threshold_value = 247
_, binary_image = cv2.threshold(blurred_img, threshold_value, 255, cv2.THRESH_BINARY + cv2.THRESH_OTSU)
cv2.imshow('binary', binary_image)
contours, _ = cv2.findContours(binary_image, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE)
image_with_contours = img.copy()
cv2.drawContours(image_with_contours, contours, -1, (0, 255, 0), 2)
cv2.imshow('Image with Contours', image_with_contours)
cv2.waitKey(0)
cv2.destroyAllWindows()
结果:
灰度:
均值滤波:
otsu分割法:
画边框:
缺点:物体白色的部分和背景相像,有什么好的办法能画边框不?