当前位置:Gxl网 > 互联网 > 图片识别最大外接红矩形并切存

图片识别最大外接红矩形并切存

时间:2021-07-01 10:21:17 帮助过:5人阅读


import cv2
import numpy as np
#from PIL import  Image

def separate_color_red(img):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)
    lower_hsv = np.array([0, 43, 46])
    high_hsv = np.array([10, 255, 255])
    mask = cv2.inRange(hsv, lowerb=lower_hsv, upperb=high_hsv)
    return mask



if __name__ == "__main__":
    # img_ =  Image.open("D:/test/71724.png")
    
    img = cv2.imread("D:/test/71724.png")
    img_separate = separate_color_red(img)
    image, contours, hier = cv2.findContours(img_separate, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    x1,y1 = np.amin(contours[0], axis = 0)[0]
    x2,y2 = np.amax(contours[0], axis = 0)[0]

    ROI = img[y1:y2, x1:x2]
    cv2.imwrite("D:/543210.jpg",ROI)

    #ROI = img_.crop((x1,y1,x2,y2))
    #ROI.save("D:/54321.jpg")