SoFunction
Updated on 2024-12-20

Example of Python-OpenCV Implementation for Image Defect Detection

The following image defect detection is implemented on Jupyter Notebook using Python+opencv. For the installation of opencv library you can refer to:Summary of the installation process and some issues with the opencv library under Python

1.Realization code

import cv2
import numpy
from PIL import Image, ImageDraw, ImageFont

# Used to add Chinese characters to images
def ImgText_CN(img, text, left, top, textColor=(0, 255, 0), textSize=20):
    if (isinstance(img, )):  # Determine if it is an OpenCV image type
        img = ((img, cv2.COLOR_BGR2RGB))
    draw = (img)
    fontText = ("font/", textSize, encoding="utf-8")
    ((left, top), text, textColor, font=fontText)
return ((img), cv2.COLOR_RGB2BGR)

#Read the original image
image0=("")
("image0", image0)
# Grayscale conversion
gray0 = (image0, cv2.COLOR_RGB2GRAY)
("gray0", gray0)for i in range(1,6):
    img0=(str(i)+".bmp")#Original picture
    img=((str(i)+".bmp"),cv2.COLOR_RGB2GRAY)# Grayscale map
    # Use the calcHist() function to calculate a histogram reflecting the distribution of gray values
    hist = ([gray0], [0], None, [256], [0.0,255.0])
    h1 = ([img], [0], None, [256], [0.0,255.0]) 
    #Calculate image similarity
    result = (hist,h1,method=cv2.HISTCMP_BHATTACHARYYA)#Barometer distance comparison, the smaller the value the higher the correlation, the maximum value is 1 and the minimum value is 0
    #print(result)
    #Set the threshold to 0.1, if the similarity is less than 0.1 then it is qualified, otherwise it is not qualified
    if result <0.1:
        detect=ImgText_CN(img0, 'Qualified', 10, 10, textColor=(255, 0, 0), textSize=30)
    else:
        detect=ImgText_CN(img0, 'Failed', 10, 10, textColor=(255, 0, 0), textSize=30)
    ("Detect_" +str(i),detect)
(0)

2. Running results

This article on Python-OpenCV to achieve image defect detection examples of the article is introduced to this, more related OpenCV image defect detection content please search my previous posts or continue to browse the following related articles I hope you will support me in the future!