这组程式是用来判断饼乾的颜色是否烤焦,不只可以应用在食品业上,在工业上也可以判断金属在热处理后的颜色等等。撷取图片的部分像下面一样,把饼乾撷取出来尽量不要有背景对影像处理比较好,使用HSV的原因是在辨识烤焦时HSV是一个比较powreful的工具,所以使用HSV影像来做直方图比对。(最后下面形态学做比较多次的原因是因为原本这组程式是用在形状比较複杂的饼乾上,可是因为有签保密协定所以不能将图片公布)
import cv2 as cvimport numpy as npimport matplotlib.pyplot as plt#这个专案是先将图中的饼乾撷取,所以前面做一些形态学把连通区找出...#将图片找出后再将其转换成HSV进行颜色比对来判断饼乾是否烤焦#using morphology to find the cookies#and convert to HSV image to judging cookies is normal or overcookdef eggroll(im,im1): global date date=cv.absdiff(im, im1) return datedef binary(date): global binaryim ret,binaryim=cv.threshold(date, 10, 255, cv.THRESH_BINARY) return binaryimdef close(binaryim): global closing kernel=np.ones((15, 15),np.uint8) clim0=cv.morphologyEx(binaryim,cv.MORPH_CLOSE,kernel) closing=cv.morphologyEx(clim0,cv.MORPH_CLOSE,kernel) return closingdef open(closing): global opening kernel=np.ones((15, 15),np.uint8) op=cv.morphologyEx(closing,cv.MORPH_OPEN,kernel) opening=cv.morphologyEx(op,cv.MORPH_OPEN,kernel) return openingdef findedge(img1,img0): global conim contours,conim=cv.findContours(img1, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) c = max(contours, key = cv.contourArea) x,y,w,h = cv.boundingRect(c) cv.rectangle(img1,(x, y), (x+w, y+h), (0, 255, 0), 2) crop_img = im0[y:y+h, x:x+w] return crop_imgdef findedge2(img3,img4): global conim2 contours1,conim1=cv.findContours(img3, cv.RETR_TREE, cv.CHAIN_APPROX_SIMPLE) c1 = max(contours1, key = cv.contourArea) x1,y1,w1,h1 = cv.boundingRect(c1) cv.rectangle(im4,(x1, y1), (x1+w1, y1+h1), (0, 255, 0), 2) crop_img2 = im4[y1:y1+h1, x1:x1+w1] return crop_img2def hsv(im5,im6): img2 = cv.cvtColor(im5, cv.COLOR_BGR2HSV) img6 = cv.cvtColor(im6, cv.COLOR_BGR2HSV) h, s, v = img2[:, :, 0], img2[:, :, 1], img2[:, :, 2] hist_h = cv.calcHist([h], [0], None, [256], [0, 256]) hist_s = cv.calcHist([s], [0], None, [256], [0, 256]) hist_v = cv.calcHist([v], [0], None, [256], [0, 256]) h1, s1, v1 = img6[:, :, 0], img6[:, :, 1], img6[:, :, 2] hist_h1 = cv.calcHist([h1], [0], None, [256], [0, 256]) hist_s1 = cv.calcHist([s1], [0], None, [256], [0, 256]) hist_v1 = cv.calcHist([v1], [0], None, [256], [0, 256]) match1 = cv.compareHist(hist_h, hist_h1, cv.HISTCMP_BHATTACHARYYA) match2 = cv.compareHist(hist_h, hist_h1, cv.HISTCMP_CORREL) match3 = cv.compareHist(hist_v, hist_v1, cv.HISTCMP_CHISQR) return match2def judgment(match2): date=match2 if date>=0.95: print('excellent') elif date>=0.9: print('great') elif date>=0.85: print('normal') else: print('fail') returnim0=cv.imread('dark2.jpg')im=cv.imread('dark2.jpg',0)im1=cv.imread('bg.jpg',0)im3=cv.imread('light3.jpg',0)im4=cv.imread('light3.jpg')v=eggroll(im, im1)v1=binary(v)v2=close(v1)v3=open(v2)v4=findedge(v3, im)v5=eggroll(im3,im1)v6=binary(v5)v7=close(v6)v8=open(v7)v9=findedge2(v8,im4)v10=hsv(v4,v9)print('correlation',v10)v11=judgment(v10)print('judgment',v11)cv.imshow("cropd",v9)cv.imshow("cropped", v4)cv.waitKey(0)