使用OpenCV计算滑块缺口

1.参考文章:https://blog.csdn.net/qq_27371025/article/details/133072065
2.实现过程:接口中传入base64 图片,base64转化为image ,通过图片获取缺口信息
实现步骤:
2.1 安装:cv2
opencv-python 是 OpenCV(Open Source Computer Vision Library)的 Python 绑定。OpenCV 是一个开源的计算机视觉和机器学习库,包含了大量的图像处理函数和计算机视觉算法。通过 opencv-python,Python 开发者能够方便地使用这些功能和算法来处理图像和视频数据。

pip install opencv-python
pip install opencv-contrib-python
def show(name):
    '''展示圈出来的位置'''
    cv2.imshow('Show', name)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

def _tran_canny(image):
    """消除噪声"""
    image = cv2.GaussianBlur(image, (3, 3), 0)
    return cv2.Canny(image, 50, 150)


def detect_displacement(img_slider_path, image_background_path):
    """detect displacement"""
    # # 参数0是灰度模式
    image = cv2.imread(img_slider_path, 0)
    template = cv2.imread(image_background_path, 0)

    # 寻找最佳匹配
    res = cv2.matchTemplate(_tran_canny(image), _tran_canny(template), cv2.TM_CCOEFF_NORMED)
    # 最小值,最大值,并得到最小值, 最大值的索引
    min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(res)

    top_left = min_loc[0]  # 横坐标
    # 展示圈出来的区域
    x, y = min_loc  # 获取x,y位置坐标
    w, h = image.shape[::-1]  # 宽高
    cv2.rectangle(template, (x, y), (x+w, y+h), (0, 0, 255), 2) #左上 右下 边框颜色,线条厚度
    # show(template)
    top_left = x+w
    return top_left

def base64_change_image(base64_str,type):
    # 移除base64字符串中的前缀(例如 'data:image/jpeg;base64,')
    base64_img_bytes = base64_str.split(',')[1]
    # 解码base64字符串为字节
    img_bytes = base64.b64decode(base64_img_bytes)
    # 将字节转换为numpy数组
    nparr = np.frombuffer(img_bytes, np.uint8)
    # 将numpy数组转换为OpenCV图像
    img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
    # 检查图像是否正确加载
    if img is None:
        print("Error: 图像未正确加载")
    else:
        if type == "left":
            cv2.imwrite('img/left.jpg', img)
            return "img/left.jpg"
        elif type == "back":
            cv2.imwrite('img/back.jpg', img)
            return "img/back.jpg"
        else:
            cv2.imwrite('img/icon.jpg', img)
            return "img/icon.jpg"


def get_click_points(image_path):
    # 读取图片
    image = cv2.imread(image_path)
    # 转换为灰度图
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    # 二值化处理
    _, thresh = cv2.threshold(gray, 127, 255, cv2.THRESH_BINARY_INV)
    # 查找轮廓
    contours, _ = cv2.findContours(thresh, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

    # 遍历轮廓,寻找点
    points = []
    for contour in contours:
        # 获取轮廓的边界框
        x, y, w, h = cv2.boundingRect(contour)
        # 可以根据实际情况过滤小轮廓
        if w > 5 and h > 5:
            # 标记轮廓
            cv2.rectangle(image, (x-10, y), (x + w-10, y + h), (0, 255, 0), 2)
            # 保存点击位置
            points.append((x + w // 2, y + h // 2))

    # 显示图片
    cv2.imshow('Image with points', image)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

    return points


@app.route('/SlidingBlock')
def sliding_block():
    start_now = datetime.now()
    start_now_time = start_now.strftime("%Y-%m-%d %H:%M:%S")
    print("开始时间:", start_now_time)
    date = request.get_json()
    left_image_str = date['left_image']
    left_image = base64_change_image(left_image_str, "left")
    back_image_str = date['back_image']
    back_image = base64_change_image(back_image_str, "back")
    skewing = detect_displacement(left_image, back_image)
    print(f"偏移:{skewing}")
    data = {'skewing': skewing}
    last_now = datetime.now()
    last_now_time = last_now.strftime("%Y-%m-%d %H:%M:%S")
    print("结束时间:", last_now_time)
    return jsonify(data)
  • 5
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
易语言使用OpenCV处理像时,可以使用以下步骤来实现缺口检测: 1. 首先,确保你已经安装了OpenCV库并且在易语言中正确引用了该库。 2. 使用`Img_New`函数创建一个像对象,并使用`Img_Load`函数加载待处理的像。 3. 使用`Img_GetSize`函数获取像的宽度和高度。 4. 创建一个与原像大小相同的灰度像对象,可以使用`Img_New`函数创建。 5. 使用`Img_Gray`函数将原像转换为灰度像。 6. 创建一个与原像大小相同的二值化像对象,可以使用`Img_New`函数创建。 7. 使用`Img_Binary`函数将灰度像转换为二值化像。你可以根据具体需求选择不同的二值化方法,比如基于阈值的二值化或自适应二值化。 8. 使用形态学操作(如腐蚀和膨胀)对二值化像进行处理,以便更好地识别缺口。可以使用`Img_Erode`和`Img_Dilate`函数来实现这些操作。 9. 使用`Img_FindContours`函数查找像中的轮廓。可以通过设定一些参数来控制轮廓的查找方式,例如最小面积、最大面积等。 10. 遍历所有找到的轮廓,使用`Img_DrawContours`函数将其绘制到原像上。 11. 最后,使用`Img_Show`函数显示处理后的像。 以上是一个基本的缺口检测流程,你可以根据具体需求进行调整和优化。注意,在易语言中使用OpenCV可能存在一些限制和不便之处,因为OpenCV是用C++编写的,而易语言是基于VB的。因此,你可能需要使用一些易语言的外部调用功能来实现一些高级的操作。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值