Opencv+Python實現缺陷檢測


實驗七、缺陷檢測

一、 題目描述

​ 對下面的圖片進行缺陷檢測操作,請詳細地記錄每一步操作的步驟。

​ 第一站圖片是標准樣品,后面幾張圖中有幾個樣品有瑕疵,需要你通過計算在圖片上顯示出哪張是合格,哪張不合格。

img img img 4 5 **1.思路**

​ Python-Opencv中用compareHist函數進行直方圖比較進而對比圖片

圖像直方圖

圖像直方圖是反映一個圖像像素分布的統計表,其實橫坐標代表了圖像像素的種類,可以是灰度的,也可以是彩色的。縱坐標代表了每一種顏色值在圖像中的像素總數或者占所有像素個數的百分比。
圖像是由像素構成,因為反映像素分布的直方圖往往可以作為圖像一個很重要的特征。在實際工程中,圖像直方圖在特征提取、圖像匹配等方面都有很好的應用。

直方圖比較

1.圖像相似度比較

如果我們有兩張圖像,並且這兩張圖像的直方圖一樣,或者有極高的相似度,那么在一定程度上,我們可以認為這兩幅圖是一樣的,這就是直方圖比較的應用之一。

2.分析圖像之間關系
兩張圖像的直方圖反映了該圖像像素的分布情況,可以利用圖像的直方圖,來分析兩張圖像的關系。

直方圖比較函數

cv2.compareHist(H1, H2, method)
其中:

  • H1,H2 分別為要比較圖像的直方圖

  • method - 比較方式

比較方式(method)

  • 相關性比較 (method=cv.HISTCMP_CORREL) 值越大,相關度越高,最大值為1,最小值為0
  • 卡方比較(method=cv.HISTCMP_CHISQR 值越小,相關度越高,最大值無上界,最小值0
  • 巴氏距離比較(method=cv.HISTCMP_BHATTACHARYYA) 值越小,相關度越高,最大值為1,最小值為0

二、 實現過程

1.給圖片添加文字的函數

#用於給圖片添加中文字符
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  #判斷是否為OpenCV圖片類型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc', textSize, encoding="utf-8")
    draw.text((left, top), text, textColor, font=fontText)
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

2.比較相關性並繪制文字

def compare(result,img0,i):
    if result >0.9:
        detect=ImgText_CN(img0, '合格', 10, 10, textColor=(255, 0, 0), textSize=30)
    else:
        detect=ImgText_CN(img0, '不合格', 10, 10, textColor=(255, 0, 0), textSize=30)
    cv2.imshow("Detect_%d"%(i),detect)
    key = cv2.waitKey(0)
    if key==27: #按esc鍵時,關閉所有窗口
        print(key)
        cv2.destroyAllWindows()

3.創建灰度直方圖

def create_hist(img):
    img = cv2.imread(img)              #讀取圖片
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    #將圖片轉化為8bit灰度圖

    plt.imshow(img_gray, cmap=plt.cm.gray)               #顯示圖片

    hist = cv2.calcHist([img], [0], None, [256], [0, 256])    #灰度直方圖
  
    plt.figure()
    plt.title("Grayscale Histogram")
    plt.xlabel("Bins")
    plt.ylabel("# of Pixels")
    plt.plot(hist)
    plt.xlim([0, 256])
    plt.show()
    return hist

4.完整代碼

%matplotlib inline
from matplotlib import pyplot as plt
import cv2
import numpy as np
from PIL import Image, ImageDraw, ImageFont

#用於給圖片添加中文字符
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, np.ndarray)):  #判斷是否為OpenCV圖片類型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    draw = ImageDraw.Draw(img)
    fontText = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc', textSize, encoding="utf-8")          ##中文字體
    draw.text((left, top), text, textColor, font=fontText)     #寫文字
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)

def compare(result,img0,i):
    if result >0.9:                              #相關性大於0.9為合格,反之為不合格
        detect=ImgText_CN(img0, '合格', 10, 10, textColor=(255, 0, 0), textSize=30)
    else:
        detect=ImgText_CN(img0, '不合格', 10, 10, textColor=(255, 0, 0), textSize=30)
    cv2.imshow("Detect_%d"%(i),detect)          #顯示繪制后的圖片
    key = cv2.waitKey(0)
    if key==27: #按esc鍵時,關閉所有窗口
        print(key)
        cv2.destroyAllWindows()
    
def create_hist(img):
    img = cv2.imread(img)              #讀取圖片
    img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)    #將圖片轉化為8bit灰度圖

    plt.imshow(img_gray, cmap=plt.cm.gray)               #顯示圖片
    hist = cv2.calcHist([img], [0], None, [256], [0, 256])    #灰度直方圖 
    plt.figure()
    plt.title("Grayscale Histogram")
    plt.xlabel("Bins")
    plt.ylabel("# of Pixels")
    plt.plot(hist)
    plt.xlim([0, 256])
    plt.show()
    return hist

hist1=create_hist("0.png")              #給標准樣品繪制直方圖
for i in range(1,6):
    print(i)                              #打印圖片序號
    img=cv2.imread("%d.bmp"%(i),1)         
    hist2=create_hist("%d.bmp"%(i))       #給測試樣品繪制直方圖   
    match1 = cv2.compareHist(hist1, hist2, cv2.HISTCMP_BHATTACHARYYA)   #返回巴氏距離
    match2 = cv2.compareHist(hist1, hist2, cv2.HISTCMP_CORREL)         #返回相關性
    print("巴氏距離:%s, 相關性:%s" %(match1, match2))
    print("\n")
    compare(match2,img,i)                             #比較並繪制

三、 運行結果(效果)

四、 問題及解決方法

  1. 中文無法輸入,解決方案:引入中文字體

五、 實驗總結

通過查閱資料,學習了OpenCV的缺陷檢測技術,提升了自己的能力。

實驗參考:https://blog.csdn.net/qq_44262417/article/details/89217011


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM