【问题标题】:how to crop detected barcode from image in python?如何从python中的图像中裁剪检测到的条形码?
【发布时间】:2020-03-07 06:36:28
【问题描述】:

我正在尝试从图像中检测条形码并从图像中裁剪检测到的条形码形状

import numpy as np
import cv2

# load the image and convert it to grayscale
image = cv2.imread("img_00100.jpg")

#resize image
image = cv2.resize(image,None,fx=0.7, fy=0.7, interpolation = cv2.INTER_CUBIC)

#convert to grayscale
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

#calculate x & y gradient
gradX = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 1, dy = 0, ksize = -1)
gradY = cv2.Sobel(gray, ddepth = cv2.CV_32F, dx = 0, dy = 1, ksize = -1)

# subtract the y-gradient from the x-gradient
gradient = cv2.subtract(gradX, gradY)
gradient = cv2.convertScaleAbs(gradient)

# blur the image
blurred = cv2.blur(gradient, (3, 3))

# threshold the image
(_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)

# construct a closing kernel and apply it to the thresholded image
kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)


# perform a series of erosions and dilations
closed = cv2.erode(closed, None, iterations = 4)
closed = cv2.dilate(closed, None, iterations = 4)


# find the contours in the thresholded image, then sort the contours
# by their area, keeping only the largest one
cnts,hierarchy = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL,cv2.CHAIN_APPROX_SIMPLE)

c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
c1 = sorted(cnts, key = cv2.contourArea, reverse = True)[1]

# compute the rotated bounding box of the largest contour
rect = cv2.minAreaRect(c)
x,y,w,h=cv2.boxPoints(rect)
image1=image.copy()
cropped = image1[int(round(y[0])):int(round(y[0]))+int(round(h[0])),int(round(x[0])):int(round(x[0]))+int(round(w[0]))]
box = np.int0(cv2.boxPoints(rect))
cv2.imshow("image",cropped)
# draw a bounding box arounded the detected barcode and display the
# image
cv2.drawContours(image, [box], -1, (0, 255, 0), 3)

#image = cv2.resize(image, None, fx=0.5, fy=0.5, interpolation = cv2.INTER_CUBIC)

cv2.imshow("Image2", image)
cv2.waitKey(0)

从上面的代码中,它成功地检测到了条形码,但它没有裁剪和显示裁剪的图像,请帮助我:

图片

【问题讨论】:

    标签: python image numpy barcode


    【解决方案1】:

    您需要计算box 变量中顶点的minmax 值,并使用它们对图像进行切片以获得裁剪后的条形码,如下所示:

    min_y = int(np.min(box[:,-1]))
    max_y = int(np.max(box[:,-1]))
    min_x = int(np.min(box[:,0]))
    max_x = int(np.max(box[:,0]))
    image = image[min_y:max_y, min_x:max_x]
    

    这是完整的示例:
    用法: python detect_barcode.py --image path_to_image

    # import the necessary packages
    import numpy as np
    import argparse
    import imutils
    import cv2
    
    # construct the argument parse and parse the arguments
    ap = argparse.ArgumentParser()
    ap.add_argument("-i", "--image", required = True, help = "path to the image file")
    args = vars(ap.parse_args())
    
    # load the image
    image = cv2.imread(args["image"])
    # convert it to grayscale
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # compute the Scharr gradient magnitude representation of the images
    # in both the x and y direction using OpenCV 2.4
    ddepth = cv2.cv.CV_32F if imutils.is_cv2() else cv2.CV_32F
    gradX = cv2.Sobel(gray, ddepth = ddepth, dx = 1, dy = 0, ksize = -1)
    gradY = cv2.Sobel(gray, ddepth = ddepth, dx = 0, dy = 1, ksize = -1)
    
    # subtract the y-gradient from the x-gradient
    gradient = cv2.subtract(gradX, gradY)
    gradient = cv2.convertScaleAbs(gradient)
    
    # blur and threshold the image
    blurred = cv2.blur(gradient, (9, 9))
    (_, thresh) = cv2.threshold(blurred, 225, 255, cv2.THRESH_BINARY)
    
    # construct a closing kernel and apply it to the thresholded image
    kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 7))
    closed = cv2.morphologyEx(thresh, cv2.MORPH_CLOSE, kernel)
    
    # perform a series of erosions and dilations
    closed = cv2.erode(closed, None, iterations = 4)
    closed = cv2.dilate(closed, None, iterations = 4)
    
    # find the contours in the thresholded image, then sort the contours
    # by their area, keeping only the largest one
    cnts = cv2.findContours(closed.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    cnts = imutils.grab_contours(cnts)
    c = sorted(cnts, key = cv2.contourArea, reverse = True)[0]
    
    # compute the rotated bounding box of the largest contour
    rect = cv2.minAreaRect(c)
    box = cv2.cv.BoxPoints(rect) if imutils.is_cv2() else cv2.boxPoints(rect)
    box = np.int0(box)
    
    # draw a bounding box arounded the detected barcode and display the
    min_y = int(np.min(box[:,-1]))
    max_y = int(np.max(box[:,-1]))
    min_x = int(np.min(box[:,0]))
    max_x = int(np.max(box[:,0]))
    image = image[min_y:max_y, min_x:max_x]
    # save cropped image
    cv2.imwrite("cropped.jpg", image)
    

    输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-09
      • 2018-01-27
      • 2021-09-06
      • 1970-01-01
      • 2017-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多