程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python+opencv to realize image edge detection (sliding adjustment threshold)

編輯:Python

Python+OpenCv Realize image edge detection ( Sliding adjustment threshold )

  • One 、 Preface
  • Two 、 The import module
  • 3、 ... and 、 Core code
    • 1. Image preprocessing
    • 2. Sliding parameter adjustment
    • 3. edge detection
    • 4. Image saving
    • 5. The main function
  • Four 、 Running results
  • 5、 ... and 、 Complete code
  • 6、 ... and 、 Program packaging
  • 7、 ... and 、 Conclusion

One 、 Preface

Be free and at leisure , Help grandma's roommate process the image . Spent a day studying cv2 Some of the functions in , Refer to other bloggers' excellent codes , On this basis, it is mixed and enriched , Made an image edge detection program , The threshold and other parameters can be adjusted in real time through the sliding bar , And can choose whether to save the image . Finally through pyinstaller Package the program into .exe Send the file to your roommate for use .
( Learning image processing for the first time and writing articles for the first time , If there is a mistake , Welcome to correct )

Two 、 The import module

Use cv2 modular (opencv-python)
Enter instructions in the terminal :pip install opencv-python install cv2
Import after successful installation cv2

import cv2

3、 ... and 、 Core code

1. Image preprocessing

Enter three parameters , When the flag bit is 1 Time indicates that the method is used to process the image
By default Gauss filtering + Histogram equalization Methods

def image_processing(img, Gauss_flag=1, Color_flag=1, Gray_flag=0): # Image preprocessing 
# Gaussian filter smoothes the image 
if Gauss_flag == 1:
img = cv2.GaussianBlur(img, (3, 3), 0)
# Equalize the histogram of color image 
if Color_flag == 1:
img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# Convert a color image to a grayscale image , Histogram of balanced gray image 
if Gray_flag == 1:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
img = cv2.equalizeHist(img)
return img

2. Sliding parameter adjustment

Create a slider , Each control cv2.Canny Each parameter in the function
Canny(image, threshold1, threshold2, edges=None, apertureSize=None, L2gradient=None)

cv2.createTrackbar('threshold1', 'Canny', 50, 300, nothing) # threshold 1
cv2.createTrackbar('threshold2', 'Canny', 100, 300, nothing) # Larger threshold 2 It is used to detect obvious edges in the image 
cv2.createTrackbar('apertureSize', 'Canny', 0, 2, nothing) # Sobel Operator size (3,5,7)
cv2.createTrackbar('L2gradient', 'Canny', 0, 1, nothing) # Parameters ( Boolean value ):true: Use more precise L2 norm ( The sum of the squares of the reciprocal in both directions is reopened ),false: Use L1 norm ( Add the absolute values of the two directional derivatives directly )

Read and return the value of the slider position in real time

threshold1 = cv2.getTrackbarPos('threshold1', 'Canny') # threshold 1
threshold2 = cv2.getTrackbarPos('threshold2', 'Canny') # threshold 2
L2gradient = cv2.getTrackbarPos('L2gradient', 'Canny') # Parameters 
aperturesize = cv2.getTrackbarPos('apertureSize', 'Canny') # Sobel Operator size 
size = aperturesize * 2 + 3 # Sobel Operator size (3,5,7)

3. edge detection

Use cv2 Medium Canny Function for edge detection , And display the image through the window

# Canny edge detection 
img_edges = cv2.Canny(img, threshold1, threshold2, apertureSize=size, L2gradient=L2gradient)
# Show edge image 
cv2.imshow('Canny', img_edges)

4. Image saving

Test button , Press q sign out , Do not save the image ; Press s sign out , Save image .
( The saved image path is the same as the original image , Named output.jpg)

if cv2.waitKey(1) == ord('q'): # sign out 
break
elif cv2.waitKey(1) == ord('s'): # Save image 
cv2.imwrite('\\'.join(img_path.split('\\')[:-1]) + '\\output.jpg', img_edges)
print(" Image saved successfully ")
break

5. The main function

Input the image address and three parameters of the image preprocessing function .
First, preprocess the image , And then edge detection .

if __name__ == "__main__":
img_path = input(" Please enter the picture address ( Such as E:\\Code\\xx.jpg):")
guass_flag = int(input(" Whether Gaussian filtering is performed ( Input 1 Conduct , Input 0 Don't make ):"))
color_flag = int(input(" Whether the color image is balanced ( Input 1 Conduct , Input 0 Don't make ):"))
gray_flag = int(input(" Whether to balance the gray image ( Input 1 Conduct , Input 0 Don't make ):"))
# Load the image 
image = cv2.imread(img_path)
# Image preprocessing 
img = image_processing(image, Gauss_flag=guass_flag, Color_flag=color_flag, Gray_flag=gray_flag)
# Show the original image 
cv2.imshow('Original', image)
# Display the preprocessed image 
cv2.imshow('Pretreatment', img)
# Image edge detection 
image_canny(img)

Four 、 Running results

Original image :
Pre processed image :

Image edge detection :
Saved image :

5、 ... and 、 Complete code

import cv2
def nothing(): # Define callback function 
pass
def image_processing(img, Gauss_flag=1, Color_flag=1, Gray_flag=0): # Image preprocessing 
# Gaussian filter smoothes the image 
if Gauss_flag == 1:
img = cv2.GaussianBlur(img, (3, 3), 0)
# Equalize the histogram of color image 
if Color_flag == 1:
img = cv2.cvtColor(img, cv2.COLOR_BGR2YUV)
# Histogram of balanced gray image 
if Gray_flag == 1:
img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Convert a color image to a grayscale image 
img = cv2.equalizeHist(img)
return img
def image_canny(img): # Image edge detection 
# Settings window 
cv2.namedWindow('Canny')
# Create a slider , Control each parameter separately 
cv2.createTrackbar('threshold1', 'Canny', 50, 300, nothing) # threshold 1
cv2.createTrackbar('threshold2', 'Canny', 100, 300, nothing) # Larger threshold 2 It is used to detect obvious edges in the image 
# cv2.createTrackbar('apertureSize', 'Canny', 0, 2, nothing) # Sobel Operator size (3,5,7)
cv2.createTrackbar('L2gradient', 'Canny', 0, 1,
nothing) # Parameters ( Boolean value ):true: Use more precise L2 norm ( The sum of the squares of the reciprocal in both directions is reopened ),false: Use L1 norm ( Add the absolute values of the two directional derivatives directly )
while (1):
# Returns the value of the position of the slider 
threshold1 = cv2.getTrackbarPos('threshold1', 'Canny') # threshold 1
threshold2 = cv2.getTrackbarPos('threshold2', 'Canny') # threshold 2
L2gradient = cv2.getTrackbarPos('L2gradient', 'Canny') # Parameters 
# aperturesize = cv2.getTrackbarPos('apertureSize', 'Canny') # Sobel Operator size 
# size = aperturesize * 2 + 3 # Sobel Operator size (3,5,7)
# Canny edge detection 
img_edges = cv2.Canny(img, threshold1, threshold2, L2gradient=L2gradient)
# Show edge image 
cv2.imshow('Canny', img_edges)
if cv2.waitKey(1) == ord('q'): # Press q sign out 
break
elif cv2.waitKey(1) == ord('s'): # Press s Save the image to the directory where the original image is located , Name it output.jpg, Quit again ![ Please add a picture description ](https://img-blog.csdnimg.cn/28c23587576b4e50a8f9f1522fd67c1e.png?x-oss-process=image/watermark,type_d3F5LXplbmhlaQ,shadow_50,text_Q1NETiBA5Zu-5Y2XX1RyZW4=,size_15,color_FFFFFF,t_70,g_se,x_16)
cv2.imwrite('\\'.join(img_path.split('\\')[:-1]) + '\\output.jpg', img_edges)
print(" Image saved successfully ")
break
cv2.destroyAllWindows()
if __name__ == "__main__":
img_path = input(" Please enter the picture address ( Such as E:\\Code\\xx.jpg):") # Enter the original image address 
guass_flag = int(input(" Whether Gaussian filtering is performed ( Input 1 Conduct , Input 0 Don't make ):")) # Input 1 For Gaussian filtering , Input 0 For not to proceed 
color_flag = int(input(" Whether the color image is balanced ( Input 1 Conduct , Input 0 Don't make ):")) # Input 1 For color image equalization , Input 0 For not to proceed 
gray_flag = int(input(" Whether to balance the gray image ( Input 1 Conduct , Input 0 Don't make ):")) # Input 1 For gray image equalization , Input 0 For not to proceed 
# Load the image 
image = cv2.imread(img_path)
# Image preprocessing 
img = image_processing(image, Gauss_flag=guass_flag, Color_flag=color_flag, Gray_flag=gray_flag)
# Show the original image 
cv2.imshow('Original', image)
# Display the preprocessed image 
cv2.imshow('Pretreatment', img)
# Image edge detection 
image_canny(img)

6、 ... and 、 Program packaging

Enter instructions in the terminal :pip install pyinstaller install pyinstaller
After successful installation, enter the command :pyinstaller -F canny.py Package the files


7、 ... and 、 Conclusion

A literary creation 、 Difficult to adjust parameters , Ask for a little favor QAQ


  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved