這組程式是用來判斷餅乾的顏色是否烤焦,不只可以應用在食品業上,在工業上也可以判斷金屬在熱處理後的顏色等等。擷取圖片的部分像下面一樣,把餅乾擷取出來盡量不要有背景對影像處理比較好,使用HSV的原因是在辨識烤焦時HSV是一個比較powreful的工具,所以使用HSV影像來做直方圖比對。(最後下面形態學做比較多次的原因是因為原本這組程式是用在形狀比較複雜的餅乾上,可是因為有簽保密協定所以不能將圖片公布)
import cv2 as cv
import numpy as np
import matplotlib.pyplot as plt
#這個專案是先將圖中的餅乾擷取,所以前面做一些形態學把連通區找出...
#將圖片找出後再將其轉換成HSV進行顏色比對來判斷餅乾是否烤焦
#using morphology to find the cookies
#and convert to HSV image to judging cookies is normal or overcook
def eggroll(im,im1):
global date
date=cv.absdiff(im, im1)
return date
def binary(date):
global binaryim
ret,binaryim=cv.threshold(date, 10, 255, cv.THRESH_BINARY)
return binaryim
def 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 closing
def 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 opening
def 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_img
def 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_img2
def 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 match2
def 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')
return
im0=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)