1.函数名:imread
定义:Mat imread( const String& filename, int flags = IMREAD_COLOR );
def imread(filename, flags=None)
参数:
filename:文件名
flags:读取标识,枚举类型,可以取以下值
enum ImreadModes { IMREAD_UNCHANGED = -1, //!< If set, return the loaded image as is (with alpha channel, otherwise it gets cropped). IMREAD_GRAYSCALE = 0, //!< If set, always convert image to the single channel grayscale image (codec internal conversion). IMREAD_COLOR = 1, //!< If set, always convert image to the 3 channel BGR color image. IMREAD_ANYDEPTH = 2, //!< If set, return 16-bit/32-bit image when the input has the corresponding depth, otherwise convert it to 8-bit. IMREAD_ANYCOLOR = 4, //!< If set, the image is read in any possible color format. IMREAD_LOAD_GDAL = 8, //!< If set, use the gdal driver for loading the image. IMREAD_REDUCED_GRAYSCALE_2 = 16, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/2. IMREAD_REDUCED_COLOR_2 = 17, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/2. IMREAD_REDUCED_GRAYSCALE_4 = 32, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/4. IMREAD_REDUCED_COLOR_4 = 33, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/4. IMREAD_REDUCED_GRAYSCALE_8 = 64, //!< If set, always convert image to the single channel grayscale image and the image size reduced 1/8. IMREAD_REDUCED_COLOR_8 = 65, //!< If set, always convert image to the 3 channel BGR color image and the image size reduced 1/8. IMREAD_IGNORE_ORIENTATION = 128 //!< If set, do not rotate the image according to EXIF's orientation flag. };
作用:读取图像,flags参数取“0”或“1”比较常见,取“0”是得到的图像是灰度图像。取“1”得到三通道彩色图像。
python code import cv2 #读取指定图片灰度图片 gray_image=cv2.imread(img_path,0) #读取指定图片3通道 org_image=cv2.imread(img_path,1) #------------------------------------- #C code #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main(int argc, char** argv) { //根据图像文件路径和文件名读取图像文件 Mat src = imread("e:/TestImage/bike.jpg",1); //创建一个图像显示窗口 namedWindow("src", 0); //显示图像 imshow("src", src); //等待用户按键触发,如果没有该语句,窗口显示图像之后就自动关闭。 waitKey(0); return 0; }
2.函数名:imwrite
定义:bool imwrite( const String& filename, InputArray img, const std::vector<int>& params = std::vector<int>());
def imwrite(filename, img, params=None)
参数:
filename:文件名
img:要保存的图像
params:表示为特定格式保存的参数编码,通常直接采用默认值。
作用:保存图像。
使用示例:
python code: #保存图片至文件 cv2.imwrite("xxx", image) #--------------------------- C code: #include <opencv2/opencv.hpp> using namespace cv; using namespace std; int main(int argc, char** argv) { Mat src = imread("e:/TestImage/bike.jpg", 1); namedWindow("src", 0); imshow("src", src); imwrite("e:/TestImage/bike_write.bmp", src); waitKey(0); return 0; }
如果保存文件路径有中文可以使用一下方法来保存:
cv2.imencode('.jpg', image)[1].tofile(save_img_path)