提取图像的最小外接矩形

学习Halcon和OpenCV:

        实现提取图像的指定区域的最小外接矩形。


代码:

Halcon实现:

read_image (M1, 'C:/Users/15383/Desktop/insert/m1.jpg')

dev_close_window()
dev_open_window(0, 0, 512, 512, 'black', WindowHandle)
dev_set_draw('margin')
dev_set_line_width(3)

rgb1_to_gray(M1, GrayImage)

dev_display(M1)

threshold(GrayImage, Regions, 0, 128)

connection(Regions, ConnectedRegions)

select_shape(ConnectedRegions, SelectedRegions, 'area', 'and', 1000 , 50000)

count_obj(SelectedRegions, Number)

for i := 1 to Number by 1
    
    select_obj(SelectedRegions, ObjectSelected, i)

    smallest_rectangle2(ObjectSelected,Row, Column, Phi, Length1, Length2)

    gen_rectangle2_contour_xld(Rectangle, Row, Column, Phi, Length1, Length2)
    
    dev_display(Rectangle)
    
endfor

结果如下:

提取图像的最小外接矩形_第1张图片

 

 

 

OpenCV实现

 

import cv2 as cv
import numpy as np

if __name__ == '__main__':
    #读取图像
    image = cv.imread(r'C:\Users\15383\Desktop\insert\m1.jpg')
    #灰度化
    gray = cv.cvtColor(image,cv.COLOR_RGB2GRAY)
    #二值化
    ret,thresh = cv.threshold(gray,128,255,cv.THRESH_BINARY)
    #轮廓的提取
    contours, hierarchy = cv.findContours(thresh,cv.RETR_TREE,cv.CHAIN_APPROX_SIMPLE)
    #按照面积筛选
    for region in contours:
        #获取区域的面积
        area = cv.contourArea(region)
        if area > 1000:
            #得到图像的最小外接矩形
            rect = cv.minAreaRect(region)
            #获取矩形的四个角的左边
            box = cv.boxPoints(rect)
            box = np.int0(box)
            #显示
            cv.drawContours(image, [box],0, (0, 0, 255), 3)
    cv.imshow('image',image)
    # 释放资源
    cv.waitKey(0)
    cv.destroyAllWindows()

效果图:

提取图像的最小外接矩形_第2张图片 

你可能感兴趣的:(OpenCV,Halcon)