目录
Mat类型与数据类型对应关系:
Unsigned 8bits uchar 0~255
Mat: CV_8UC1, CV_8UC2, CV_8UC3, CV_8UC4
Signed 8bits char -128~127
Mat: CV_8SC1,CV_8SC2,CV_8SC3,CV_8SC4
Unsigned 16bits ushort 0~65535
Mat: CV_16UC1,CV_16UC2,CV_16UC3,CV_16UC4
Signed 16bits short -32768~32767
Mat: CV_16SC1,CV_16SC2,CV_16SC3,CV_16SC4
Signed 32bits int -2147483648~2147483647
Mat: CV_32SC1,CV_32SC2,CV_32SC3,CV_32SC4
Float 32bits float -1.1810-38~3.4010-38
Mat: CV_32FC1,CV_32FC2,CV_32FC3,CV_32FC4
Double 64bits double
Mat: CV_64FC1,CV_64FC2,CV_64FC3,CV_64FC4
下面是如何查看图像的Mat类型:
cout<<image.type()<<endl;
OpenCV将16位图像转为8位
16位对应ushort类型。假如直接convertTo()转换类型的话,会有失真
Mat TIFF16to8(Mat& img)
{
int width = img.cols;//图片宽度
int height = img.rows;//图片高度
Mat dst = Mat::zeros(height, width, CV_8UC1);//先生成空的目标图片
double minv = 0.0, maxv = 0.0;
double* minp = &minv;
double* maxp = &maxv;
minMaxIdx(img, minp, maxp); //取得像素值最大值和最小值
//用指针访问像素,速度更快
ushort* p_img;
uchar* p_dst;
for (int i = 0; i < height; i++)
{
p_img = img.ptr<ushort>(i);//获取每行首地址
p_dst = dst.ptr<uchar>(i);
for (int j = 0; j < width; ++j)
{
p_dst[j] = (p_img[j] - minv) / (maxv - minv) * 255;
//下面是失真较大的转换方法
//int temp = img.at<ushort>(i, j);
//dst.at<uchar>(i, j) = temp;
}
}
return dst;
}
OpenCV裁剪矩形区域赋值
Mat img;//读个图
cv::Rect rect(x, y, WIDTH, HEIGHT);//以坐标(x,y)为矩形的左上角起点,宽高为W和H的矩形
Mat tmp = img(rect);//将img上矩形框住的部分赋给tmp
OpenCV将Mat粘贴到指定位置
cv::Rect roi_rect = cv::Rect(0, 0, src.cols, src.rows);
src.copyTo(image(roi_rect));
//把src的内容复制到image指定的Rect框中
OpenCV旋转Mat
rotate(img, img_90, ROTATE_90_CLOCKWISE);
//下面是源码中参数的定义
enum RotateFlags {
ROTATE_90_CLOCKWISE = 0, //!<Rotate 90 degrees clockwise
ROTATE_180 = 1, //!<Rotate 180 degrees clockwise
ROTATE_90_COUNTERCLOCKWISE = 2, //!<Rotate 270 degrees clockwise
};
OpenCV对图像画线填充
cv::Point root_points[1][4];//初始化一组数据,四个点
root_points[0][0] = cv::Point(0,0);
root_points[0][1] = cv::Point(0,100);
root_points[0][2] = cv::Point(100,100);
root_points[0][3] = cv::Point(100,0);
const cv::Point* ppt[1] = { root_points[0] };
int npt[] = { 4 };
cv::polylines(diffuse, ppt, npt, 1, 1, Scalar(0, 0, 0), 1, 8, 0);//画线
cv::fillPoly(diffuse, ppt, npt, 1, Scalar(0, 0, 0));//填充