python OpenCV achieve defect detection

Seventh test machine vision

First, the purpose of the experiment

Experiments carried out by the seventh OpenCV, the picture defect detection.

Second, the experimental content

The picture defect measurement.

Third, the experimental process

I'm using python language + openCV the picture function defect detection. Experiment we need to import libraries have import cv2; from PIL import Image, ImageDraw, ImageFont;

1) to read the image and grayscale

We used a for loop to read all images to be detected, then grayscale using imread () function to read images,

Code examples:

img = cv2.imread("0.bmp")

gray = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)

for i in range(1, 6):

    t1=cv2.cvtColor(cv2.imread(str(i)+".bmp"),cv2.COLOR_RGB2GRAY)

Untitled .png 

Figure 3.1 graying pictures

2) histogram calculation picture

Use calcHist () function is calculated:

Example code:

# Compute the image histogram

    hist = cv2.calcHist([gray], [0], None, [256], [0.0,255.0])

    cv2.calcHist h1 = ([t1], [0], None, [256], [0.0,255.0])

3) picture font, font size

Enter the code:

# Contrast Picture similarity

    result = sum(hist - h1)[0]

    # Open the image created PIL

    im = Image.open(str(i) + ".bmp")

    # Create an operation object

    draw = ImageDraw.Draw(im)

    # Font object simsun, word size is 30,

    fnt = ImageFont.truetype(r'C:\Windows\Fonts\simsun.ttc', 30)

4) determine eligibility Pictures

Use an if statement, if the original picture contrast similarity of less than 10, qualified; otherwise unqualified.

Example code:

if result < 10:

        draw.text((5, 10), u'合格', fill='red', font=fnt)

    else:

        draw.text ((5, 10), u 'failure', fill = 'red', font = fnt)

5) show pictures

Example code:

    im.show("result"+str(i)+".png")

1.png 

Figure 3.2 shows whether or not qualified Pictures

Fourth, the experimental errors

The experiment did not encounter the big problem.

Fifth, experimental summary

Learning OpenCV defect detection technology, improve their ability.

 

Guess you like

Origin www.cnblogs.com/CJR-QYF/p/12635009.html