opencv_阈值分割

#include<opencv2\opencv.hpp>
#include<highgui.h>
#include<math.h>
#include<iostream>
using namespace std;
using namespace cv;
Mat src, dst,gray_src;
int threshold_value = 127;
int threshold_max = 255;
int type_value = 2;
int Type_max = 4;
const char* output_title = "binary image";
void Threshold_Demo(int, void*);
int main(int argc, char** argv)
{
	// read image
	src = imread("C:/Users/qxq/Pictures/image/fox.jpg");
	if (src.empty())
	{
		printf("Could not load image...");
		return -1;
	}
	char INPUT_WIN[] = "input image";
	namedWindow(INPUT_WIN, CV_WINDOW_AUTOSIZE);
	namedWindow(output_title, CV_WINDOW_AUTOSIZE);
	imshow(INPUT_WIN, src);
	
	//创建一个滚动条
	createTrackbar("T_val", output_title, &threshold_value, threshold_max, Threshold_Demo);
	createTrackbar("Type val", output_title, &threshold_value, Type_max, Threshold_Demo);

	Threshold_Demo(0,0);

	waitKey(0);
	return 0;
}

void Threshold_Demo(int, void*)
{
	cvtColor(src, gray_src, CV_BGR2GRAY);//只能用8位灰度图像
	//二值化
	//threshold(gray_src, dst, threshold_value, threshold_max, THRESH_BINARY);
	//用滚动条调整,THRESH_BINARY对应的值为0,一共有5种(0~4).
	//threshold(gray_src, dst, threshold_value, threshold_max, type_value);
	//使用OSTU自动寻找合适的阈值,有2种方法(THRESH_OTSU和THRESH_TRIANGLE)
	threshold(gray_src, dst, 0, 255, THRESH_OTSU | type_value);

	imshow(output_title, dst);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
OpenCV是一个开源的计算机视觉库,提供丰富的图像处理和计算机视觉算法。而Python是一种简单易学且功能强大的编程语言,它与OpenCV结合使用可以进行各种图像处理任务。 阈值分割是一种常用的图像分割方法,它将图像中的像素根据其灰度值与设定的阈值进行比较,将像素分为两个类别:大于阈值的像素为一类,小于阈值的像素为另一类。这种方法常用于图像二值化、目标检测、边缘检测等应用。 在OpenCV中,使用函数cv2.threshold()来实现阈值分割。该函数接受以下参数: - src:输入图像,必须是单通道灰度图像。 - thresh:设定的阈值。 - maxval:当像素值大于阈值时,所赋予的新值。 - type:阈值分割的类型,包括cv2.THRESH_BINARY、cv2.THRESH_BINARY_INV、cv2.THRESH_TRUNC、cv2.THRESH_TOZERO和cv2.THRESH_TOZERO_INV。 下面是一个示例代码,演示了如何使用OpenCV进行阈值分割: ```python import cv2 # 读取图像 image = cv2.imread('image.jpg', 0) # 以灰度模式读取图像 # 进行阈值分割 ret, threshold = cv2.threshold(image, 127, 255, cv2.THRESH_BINARY) # 显示原图和阈值分割结果 cv2.imshow('Original Image', image) cv2.imshow('Threshold Image', threshold) cv2.waitKey(0) cv2.destroyAllWindows() ``` 这段代码首先使用cv2.imread()函数读取一张灰度图像,然后使用cv2.threshold()函数进行阈值分割,将像素值大于127的像素设为255,小于等于127的像素设为0。最后使用cv2.imshow()函数显示原图和阈值分割结果。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值