OpenCV中处理遇到的一些小错与注意点

留作个人笔记,以供后需。

1. opencv只支持float32的图像显示和操作,然后float64是numpy的数据类型,opencv中不支持。在某些时候报错,需要将矩阵转为float32类型。

2. cv2.imread读出的图像为BGR模式而非RGB。

3. 图像uint8与float类型转换,uint8区间范围为0-255,而在对图片进行对比度增强,灰度等图片操作时,会引起图片像素值越界,因而在处理方法中还需要将图片矩阵像素值限制在规定范围内。虽然之前采用的方法是将图片写入存储中,之后再读取,我们可以看一下OpenCV 中imwrite函数对数据类型进行自动转换时,是根据如下的方法进行的:

Saturation Arithmetics
As a computer vision library, OpenCV deals a lot with image pixels that are often encoded in a compact, 8- or 16-bit per channel, form and thus have a limited value range. Furthermore, certain operations on images, like color space conversions, brightness/contrast adjustments, sharpening, complex interpolation (bi-cubic, Lanczos) can produce values out of the available range. If you just store the lowest 8 (16) bits of the result, this results in visual artifacts and may affect a further image analysis. To solve this problem, the so-called saturation arithmetics is used. For example, to store r, the result of an operation, to an 8-bit image, you find the nearest value within the 0..255 range:


Similar rules are applied to 8-bit signed, 16-bit signed and unsigned types. This semantics is used everywhere in the library. In C++ code, it is done using the saturate_cast<> functions that resemble standard C++ cast operations. See below the implementation of the formula provided above:

I.at<uchar>(y, x) = saturate_cast<uchar>(r);
where cv::uchar is an OpenCV 8-bit unsigned integer type. In the optimized SIMD code, such SSE2 instructions as paddusb, packuswb, and so on are used. They help achieve exactly the same behavior as in C++ code.

Note:

Saturation is not applied when the result is 32-bit integer.

而针对这个的替换处理方法使用numpy中的clip函数,将其限制在[0,255]范围内。
涉及参考:[bug] numpy.astype(uint8)和opencv imwrite函数的自动数据转换

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值