【python-opencv】对图片二值化处理后,对图像进行框标定

一、框标定代码

import cv2
import numpy as np

from sobel算子边缘检测 import sobel_cal

# 设置最小框的面积
MIN_BOX = 2500


def draw_min_rect_circle(img, cnts):  # conts = contours
    img = np.copy(img)

    for cnt in cnts:
        x, y, w, h = cv2.boundingRect(cnt)
        if w * h < MIN_BOX:
            continue
        print(x, y, x + w, y + h)
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)  # blue

    return img


# def draw_min_rect_circle(img, cnts):  # conts = contours
#     img = np.copy(img)
#
#     for cnt in cnts:
#         x, y, w, h = cv2.boundingRect(cnt)
#         if w * h < MIN_BOX:
#             continue
#         print(x, y, x + w, y + h)
#         cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)  # blue
#         break
#     return img

def run():
    imgs = cv2.imread('img/20.JPG')  # a black objects on white image is better

    # img为裁剪过后的图片,image为二值化之后的黑白图片。
    imgs, image = sobel_cal(imgs)
    # cv2.imshow("contour", image)
    # cv2.waitKey()

    thresh = cv2.GaussianBlur(image, (5, 5), 0)
    thresh = cv2.Canny(thresh, 0, 104)

    contours, hierarchy = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    # print(hierarchy, ":hierarchy")
    """
    [[[-1 -1 -1 -1]]] :hierarchy  # cv2.Canny()

    [[[ 1 -1 -1 -1]
      [ 2  0 -1 -1]
      [ 3  1 -1 -1]
      [-1  2 -1 -1]]] :hierarchy  # cv2.threshold()
    """
    # 传入的是没有高斯去噪的图片
    imgs = draw_min_rect_circle(imgs, contours)
    cv2.imshow("contours", imgs)
    cv2.waitKey()


if __name__ == '__main__':
    run()

二、结果展示

(1)待处理图像

在这里插入图片描述

(2)二值化后的图像

在这里插入图片描述

(3)框标定后的图像

在这里插入图片描述

参考

python+openCV利用函数cv2.findContours()和cv2.drawContours查找并绘制轮廓

  • 0
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值