OpenCV Quick Start 1: Image Reading & Saving

One: Introduction to OpenCV

OpenCV is a cross-platform computer vision and machine learning software library released under the Apache 2.0 license (open source), which can run on Linux, Windows, Android and Mac OS operating systems. [1] It is lightweight and efficient—consists of a series of C functions and a small number of C++ classes, and provides interfaces for languages ​​such as Python, Ruby, and MATLAB, and implements many general-purpose algorithms in image processing and computer vision.
OpenCV is written in C++ language, it has C++, Python, Java, and MATLAB interfaces, and supports Windows, Linux, Android, and Mac OS, OpenCV is mainly inclined to real-time vision applications, and utilizes MMX and SSE instructions when available, and now also Provide support for C#, Ch, Ruby, GO.

1: pycharm installation

Xiaoqi is using pycharm2021.3 here (I bought it on Xixi 3.9, and the installation tutorial is also in it)
Link: https://pan.baidu.com/s/1VfODGTu2f9foyNBKFtyG3w?pwd=4869
Extraction code: 4869
This is Xiaoqi If you are interested in the downloaded plug-ins, you can take a look
Plugin recommendation_0
Plug-in recommendation_1

Two: Python installs OpenCV

After installing pycharm, we can run the following command in the terminal to install NumPy:

pip install numpy

Then install OpenCV, you can choose two different versions:

Install only the main module package

pip install opencv-python

Install the full package (including main and add-on modules)

pip install opencv-contrib-python

At that time, the latest opencv was 4.5.2, so this series was running on 4.5.2

Three: window display related API

namedWindow()		#窗口命名
imshow()			#窗口显示
destoryALLWindows() #销毁所有窗口
resizeWindow()		#窗口显示大小更改

Four: source code

1: Read, display and save images

import cv2

img =cv2.imread(r'C:\Users\DMr\Pictures\Saved Pictures\gary.jpg')#读取
cv2.namedWindow('xianshi',cv2.WINDOW_NORMAL)#命名
cv2.resizeWindow('xianshi',640,480)#改变窗口大小
while True:
    cv2.imshow('xianshi',img)

    key=cv2.waitKey(0)#接收按键信息---16位
    if (key&0xff ==ord('q')):#esc退出--取key的最后八位
        break
    elif(key&0xff==ord('s')):#按下s保存图片
        cv2.imwrite(r'C:\Users\DMr\Pictures\cai\text.jpg',img)#保存的路径与要保存的图片
    else:
        print(key)
        
cv2.destroyAllWindows()#销毁所有窗口

output
Image display

2: One Mat displays multiple pictures

//c++
Mat src1 = imread("D:/images/1.png");
Mat src2 = imread("D:/images/t3.jpg");
imshow("src1", src1);imshow("src2", src2);
// 构建新图像的大小
int width = src1.cols + src2.cols;
int height = max(src1.rows, src2.rows);
Mat two = Mat::zeros(Size(width, height), src1.type());// 构建ROI
Rect r1(0, 0, src1.cols, src1.rows);
Rect r2(0, 0, src2.cols, src2.rows);
r2.x = src1.cols;
// 内容copy
src1.copyTo(two(r1));
src2.copyTo(two(r2));
imshow("two images demo", two);
waitKey(0);

3: cyclic reading map

//c++
#include <iostream>
#include <opencv2/opencv.hpp>

using namespace cv;
using namespace std;

Mat img;
int ImgNum = 6;
char filename[50];
char a[300]; 

int main(){
    
    
	for (int i = 0; i < ImgNum; i++) //循环读入图片 
	{
    
    
		sprintf(filename, "C:\\Users\\DMr\\Pictures\\cai\\%d.jpg", i);
		img = imread(filename,0);//0灰度,1原图

		if (img.empty())
		{
    
    
			cout << "图像加载失败!\n" << endl;
			return -1;
		}
        else
    		cout << "图像加载成功!" << endl << endl;
		namedWindow("huidu", WINDOW_NORMAL);
		int b = 0;
		for (int n = 0; n < ImgNum; n++) {
    
    
			sprintf(a, "C:\\Users\\DMr\\Pictures\\vs_baocun\\text%d.jpg",b++);
			imwrite(a, img);
		}
		imshow("huidu", img);//显示图片
		waitKey(1000);
	}
	
//waitKey(0);	
return 0;	
}
import os
import cv2
'''
读取文件夹下图片并保存到指定路径从   
'''
def read_path(file_pathname):
    #遍历该目录下的所有图片文件
    for filename in os.listdir(file_pathname):
        print(filename)#文件名
        img = cv2.imread(file_pathname+'/'+filename)
        ####change to gray
      #(下面第一行是将RGB转成单通道灰度图,第二步是将单通道灰度图转成3通道灰度图)不需要这种操作只需注释掉即可
        img=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

        cv2.imshow('s',img)
        key = cv2.waitKey(0)  # 接收按键信息---16位
        if (key & 0xff == ord('q')):  # esc退出--取key的最后八位
            break
        elif (key & 0xff == ord('s')):  # 按下s保存图片
            cv2.imwrite(r'C:\Users\DMr\Pictures\cai'+"/"+filename, img)  # 保存的路径与要保存的图片
        else:
            print(key)


        cv2.destroyAllWindows()  # 销毁所有窗口

#读取的目录
read_path("D:\\Pictures\\text")  # vscode里面读取图片文件夹的正确方式,pycharm里不知道。。。。
#print(os.getcwd())

Read position
the mayor
Effect display
insert aa image description here

4: Read floating-point type image

Mat m2;
src.convertTo(m2, CV_32F, 0.00392);
imshow("m2", m2);

It’s just that one more parameter is added during the type conversion. This parameter is 1/255 = 0.00392, which
means to convert the pixel value from 0 to 255 to a floating point number between 0 and 1, and then display it. The display result corresponds to the far right of the above picture. side.
Explanation: When imshow displays floating-point numbers, it only supports the display of floating-point numbers between 0 and 1. If it exceeds 1, it is considered white. Therefore, when the value range is not rescaled, the floating-point number Mat in the middle can only be displayed in white. .

Five: Problem Solving

If the output:
error: (-215:Assertion failed) size.width>0 && size.height>0 in function 'cv::imshow'
may be a problem with the image path, you can take a good look at the image path

Common reasons for image reading failure :

  1. The path may contain Chinese
  2. There is a problem with the path, such as: "C:\Users\DELL\Pictures\b80592ef7330bd59f63bdef7fb6ef0f.jpg"
    can be changed to r"C:\Users\DELL\Pictures\b80592ef7330bd59f63bdef7fb6ef0f.jpg"
    or "C:\Users\DELL\Pictures\b8059 2ef7330bd59f63bdef7fb6ef0f. jpg"
    or "C:/Users/DELL/Pictures/b80592ef7330bd59f63bdef7fb6ef0f.jpg"

\ in python is the meaning of the escape character

1: Chinese path reading and saving

English path usage (error): No error will be reported when reading at this time, the img is empty, and an error will be reported in some subsequent operations

img = cv2.imread("含有中文路径的图片.jpg")

use correctly

img = cv2.imdecode(np.fromfile("含有中文路径的图片.jpg",dtype=np.uint8),-1)

Corresponding to the -1 parameter in the code: cv2.IMREAD_UNCHANGED(-1):
As the name suggests, read in the complete picture, including the alpha channel. If the data does not contain an alpha channel, the gray image is read as (H, W), and the color image is read as (H, W, 3).
cv2.IMREAD_GRAYSCALE(0): Read in a grayscale image with a shape of (H, W). Colored pictures are also read as gray shapes.
cv2.IMREAD_COLOR(1): The default parameter, read in a color picture, ignore the alpha channel, and the shape is (H, W, 3). Gray maps are also read as colored shapes.

2: Save the picture with Chinese path (imwrite)

#img为需要保存的图片
cv2.imwrite("含有中文路径的图片.jpg", img)#(错误)

use correctly

# cv2.imencode(保存格式, 保存图片)[1].tofile(保存路径)
cv2.imencode('.jpg', img)[1].tofile("含有中文路径/xxx.jpg")

If you have any questions, please leave a message in the comment area and make progress together

Daily "big pie":
If you decide that the splendid mountains are unobstructed and the sea is unobstructed

Guess you like

Origin blog.csdn.net/weixin_52051554/article/details/125758858