python image recognition and cutting theme

Two ways, one is to use Baidu's API, the effect can be, but it seems there is a limit to call 50 times a day
AIP AipImageClassify Import from 
Import CV2 
"" "Your AK SK APPID" "" 
APP_ID = 'the X-' 
API_KEY = 'the X-' 
SECRET_KEY = 'XX' 
Client = AipImageClassify (APP_ID, API_KEY, SECRET_KEY) 
"" "read the image" " " 
DEF get_file_content (filePath): 
    with Open (filePath, 'RB') AS FP: 
        return fp.read () 
Image get_file_content = ( 'D: \\ before.jpg') 
" "" An optional argument "" " 
= {} Options 
"" "with a parameter called image detection body" "" 
RET = client.objectDetect (image, Options) 
Print (RET) # outputs four values, but different in the python and 
# cv2.rectangle (image, left corner, lower right corner coordinates, color,Line thickness) 
Image cv2.imread = ( 'D: \\ after.jpg') 
cv2.rectangle (Image, (24, 39), (464, 404), (0, 255, 0), 2) 
cv2.imwrite ( 'D: \\ d99.png', Image)

  Another method is a method using opencv, https://blog.csdn.net/liqiancao/article/details/55670749

       https://www.cnblogs.com/python-life/articles/8727692.html

       If the background color difference is relatively large, the effect is not bad

# - * - Coding: UTF-8 - * - 

"" " 
Author: Alan 
Email: [email protected] 
the Refer: https://blog.csdn.net/liqiancao/article/details/55670749 
Note: Using Python and OpenCV detecting objects in the image and the object cut down 
"" " 

Import CV2 
Import numpy NP aS 

# Step1: load picture, converted into grayscale 
image cv2.imread = ( 'D: \\ IMG_20190601_110701.jpg') 
Gray = cv2.cvtColor (Image, cv2.COLOR_BGR2GRAY) 

# Step2: x is calculated using Sobel operator, a gradient in the y-direction, after subtracting a gradient in the y-direction in the x direction, by the subtraction, leaves us with a high level gradient and an image region of low vertical gradient. 
= cv2.Sobel gradX (Gray, cv2.CV_32F, DX =. 1, Dy = 0, ksize = -1) 
Grady = cv2.Sobel (Gray, cv2.CV_32F, DX = 0, = Dy. 1, ksize = -1) 

Subtract The Y-gradient # from The X-gradient 
gradient = cv2.subtract (gradX, Grady)
= cv2.convertScaleAbs gradient (gradient) 
# Show Image 
# cv2.imshow ( "First", gradient) 
# cv2.waitKey () 

# Step3: removing noise on the image. First low-pass smoothing filter splash image (9 x 9 kernel), which will help to smooth the high-frequency noise in the image. 
# Target low-pass filter is to reduce the change rate of the image. As will mean replacing each pixel for the surrounding pixels. This allows smooth and substituted for those areas significant intensity variations. 
# Then, the binarized image blur. Any pixel gradient image is not greater than 90 are set to 0 (black). Otherwise, the pixel is set to 255 (white). 
The threshold and Image Blur # 
, blurred = cv2.blur (gradient, (. 9,. 9)) 
_, cv2.threshold Thresh = (, blurred, 90, 255, cv2.THRESH_BINARY) 
# SHOW the IMAGE 
# cv2.imshow ( "Thresh", Thresh) 
# cv2.waitKey () 

# step4: in the image above we see that there are many areas of the body bees black spare, we use a white fill these vacant, making it easier to identify the following program areas insect, 
# it needs to do some morphological aspects of the operation. 
kernel = cv2.getStructuringElement (cv2.MORPH_RECT, (25 , 25))
= cv2.morphologyEx Closed (Thresh, cv2.MORPH_CLOSE, Kernel) 
# Show Image 
# cv2.imshow ( "closed1", Closed) 
# cv2.waitKey () 

# STEP5: From the graph we find that there are some small image on white insect contour detection after spots, which would interfere, they should be removed. Run the four morphological erosion and expansion. 
Perform A Series of erosions # dilations and 
Closed = cv2.erode (Closed, None, Iterations =. 4) 
Closed = cv2.dilate (Closed, None, Iterations =. 4) 
# Show Image 
# cv2.imshow ( "closed2", Closed) 
cv2.waitKey # () 

# step6: identify the insect profile area. 
# Cv2.findContours () function 
# is the first parameter to be retrieved images must be bitonal, i.e., black and white (not grayscale), 
# so that the image reading is first converted to gray, and then converted into binary image, in the third step we cv2.threshold () function has been binary FIG. 
# The second parameter indicates the outline of the search mode, there are four: 
# 1. cv2.RETR_EXTERNAL represent only detect the outer contour 
# 2. cv2.RETR_LIST detect the outline does not establish hierarchical relationships
# 3. cv2.RETR_CCOMP contour establish two levels, one above the outer boundary, which is the boundary layer of the information in the bore. If there is a hole communicating the object, the object boundaries are top. 
# 4. cv2.RETR_TREE build a profile of a hierarchical tree structure. 
# Third parameter is the approximation of the contour 
# cv2.CHAIN_APPROX_NONE store all contour points, two adjacent points of difference between the pixel position does not exceed 1, i.e., max (abs (x1-x2) , abs (y2-y1) ). 1 == 
# cv2.CHAIN_APPROX_SIMPLE compression in the horizontal direction, the vertical direction, a diagonal direction of the element, leaving only the coordinates of the end point direction, for example, a rectangular profile only 4 points to save the profile information 

# cv2.findContours () function returns two values, one is the profile itself, there is a corresponding attribute for each profile. 
# Cv2.findContours () function returns the value of a first list, list element is a profile of each image, represented by the numpy ndarray. 
# Save each ndarray where are the coordinates of each point on the contour. We sort the list, the profile is the profile we are looking for the most insects point. 
cv2.findContours = X (closed.copy (), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE) 
# Import PDB 
# pdb.set_trace () 
_a, CNTs, _B = X 
C = the sorted (CNTs, cv2.contourArea Key =, = Reverse true) [0]

# OpenCV outline drawn on the image by cv2.drawContours. 
# The first parameter is indicated on the drawn contour which image 
# the second parameter is the profile itself, in Python is a list 
# contouring third parameter specifies which of the profile list, if it is -1, wherein all of the contouring 
# fourth parameter is the color of the contour line 
# fifth parameter is the thickness of the contour line 

# cv2.minAreaRect () function: 
# smallest rectangular area comprising mainly determined set point, this can have a rectangular the deflection angle, may not be parallel to the boundary of the image. 
The Rotated Compute the bounding Box # The Largest of Contour 
RECT = cv2.minAreaRect (C) 
# = RECT cv2.minAreaRect (CNTs [. 1]) 
Box = np.int0 (cv2.boxPoints (RECT)) 

# Draw the bounding Box A The arounded detected barcode and display the image 
under a production environment may not be framed # 
# cv2.drawContours (Image, [Box], -1, (0, 255, 0),. 3) 
# cv2.imshow ( "Image", Image) 
# cv2.imwrite ( "contoursImage2.jpg", Image) 
# cv2.waitKey (0)

# Step7: cropping. box is saved in the coordinates of the four vertices of the green rectangle. I press insect red rectangle image cropping FIG. 
# Find four vertices x, y coordinates of the minimum and maximum values. The new high-image = maxY-minY, width = maxX-minX. 
Xs = [I [0] for I in Box] 
Ys is = [I [. 1] for I in Box] 
X1 = min (Xs) 
X2 = max (Xs) 
Y1 = min (Ys is) 
Y2 = max (Ys is) 
Hight = Y2 - Y1 
width = X2 - X1 
cropImg Image = [Y1: Hight + Y1, X1: width X1 +] 

# Show Image 
cv2.imshow ( "cropImg", cropImg) 
cv2.imwrite ( 'D: \\ result.jpg' , cropImg) 
Print ( "DONE") 
cv2.waitKey ()

  



Guess you like

Origin www.cnblogs.com/marszhw/p/10963498.html