要求:
????????识别orange.jpg中的橙子。要求OpenCV内置函数中所有数字形式的参数随机上下波动10%以内不影响识别。
Python实现
import cv2 as cv
import matplotlib.pyplot as plt
# 打开图像
filename = './orange.jpg'
image = cv.imread(filename)
# 将BGR格式转成HSV格式
HSV = cv.cvtColor(image, cv.COLOR_BGR2HSV)
# 对饱和度通道进行5次腐蚀和5次膨胀
kernel1 = cv.getStructuringElement(cv.MORPH_RECT, (7, 7))
erosion1 = cv.erode(HSV[:,:,1],kernel1,iterations = 5)
dilation1 = cv.dilate(erosion1,kernel1,iterations = 5)
# 二值化分割,阈值设为190,浮动区间为171-209
_, bw = cv.threshold(dilation1, 190, 0xff, cv.THRESH_BINARY)
# 对二值化图片进行4次膨胀和4次腐蚀
kernel2 = cv.getStructuringElement(cv.MORPH_RECT, (5, 5))
dilation2 = cv.dilate(bw,kernel2,iterations = 4)
erosion2 = cv.erode(dilation2,kernel2,iterations = 4)
# 检测物体轮廓
cnts, _ = cv.findContours(erosion2, cv.RETR_EXTERNAL, cv.CHAIN_APPROX_SIMPLE)
# 将轮廓显示原图像上
cv.drawContours(image,cnts,0,(0,255,0),3)
# 显示结果
image2 = cv.cvtColor(image,cv.COLOR_BGR2RGB)
plt.figure()
manager = plt.get_current_fig_manager()
manager.window.showMaximized()
plt.subplot(121)
plt.title('Orange')
plt.imshow(image2)
plt.subplot(122)
plt.title('Binary')
plt.imshow(erosion2,cmap='gray')
plt.show()
C++实现
#include <opencv2/opencv.hpp>
#include <opencv2/imgproc/types_c.h>
#include <vector>
using namespace cv;
using namespace std;
int main()
{
//打开图像
Mat image = imread("./orange.jpg");
//将BGR格式转成HSV格式
Mat HSV;
cvtColor(image,HSV,CV_BGR2HSV_FULL);
//分离HSV中的S通道
vector<Mat> channels;
split(HSV, channels);
Mat S = channels.at(1);
//对饱和度通道进行5次腐蚀和5次膨胀
Mat erosion1,dilation1;
Mat kernel1 = getStructuringElement(MORPH_RECT, Size(7, 7));
erode(S, erosion1, kernel1, Point(-1,-1), 5);
dilate(erosion1, dilation1, kernel1, Point(-1,-1), 5);
//二值化分割,阈值设为190,浮动区间为171-209
Mat bw;
threshold(dilation1, bw, 171, 255, CV_THRESH_BINARY);
//对二值化图片进行4次膨胀和4次腐蚀
Mat kernel2 = getStructuringElement(MORPH_RECT, Size(5, 5));
Mat erosion2,dilation2;
dilate(bw, erosion2, kernel2, Point(-1,-1), 4);
erode(erosion2, dilation2, kernel2, Point(-1,-1), 4);
//检测物体轮廓
vector<vector<Point>> cnts;
vector<Vec4i> hier;
findContours(dilation2,cnts,hier,CV_RETR_EXTERNAL,CHAIN_APPROX_SIMPLE,Point());
//将轮廓显示原图像上
drawContours(image,cnts,0,Scalar(0,255,0),3);
//显示结果
imshow("Orange", image);
imshow("Binary",erosion2);
waitKey();
destroyAllWindows();
return 0;
}
Yolo V5实现
|