全国服务热线:

15861139266

如何使用Opencv裁剪图像_苏州机器视觉培训_苏州上位机培训_苏州工业机器人培训
发布时间:2024-04-10 16:23:11 点击次数:1944

首先,为什么我们需要裁剪?进行裁剪以从图像中删除所有不需要的对象或区域。甚至突出图像的特定特征。



以下代码片段显示了如何使用 Python 和 C++ 裁剪图像。在这篇文章中,您将详细了解这些内容。

Python

1# Import packages
2import cv2
3import numpy as np
4
5img = cv2.imread('test.jpg')
6print(img.shape) # Print image shape
7cv2.imshow("original", img)
8
9# Cropping an image
10cropped_image = img[80:280150:330]
11
12# Display cropped image
13cv2.imshow("cropped", cropped_image)
14
15# Save the cropped image
16cv2.imwrite("Cropped Image.jpg", cropped_image)
17
18cv2.waitKey(0)
19cv2.destroyAllWindows()

C++

1// Include Libraries
2#include<opencv2/opencv.hpp>
3#include<iostream>
4
5// Namespace nullifies the use of cv::function();
6using namespace std;
7using namespace cv;
8
9int main()
10{
11  // Read image
12  Mat img = imread("test.jpg");
13  cout << "Width : " << img.size().width << endl;
14  cout << "Height: " << img.size().height << endl;
15  cout<<"Channels: :"<< img.channels() << endl;
16  // Crop image
17  Mat cropped_image = img(Range(80,280), Range(150,330));
18
19  //display image
20  imshow(" Original Image", img);
21  imshow("Cropped Image", cropped_image);
22
23  //Save the cropped Image
24  imwrite("Cropped Image.jpg", cropped_image);
25
26  // 0 means loop infinitely
27  waitKey(0);
28  destroyAllWindows();
29  return 0;
30}

使用 OpenCV 进行裁剪

image.png

在这篇文章中将用于裁剪的图像。


Python:

1img=cv2.imread('test.png')
2
3# Prints Dimensions of the image
4print(img.shape)
5
6# Display the image
7cv2.imshow("original", img)
8cv2.waitKey(0)
9cv2.destroyAllWindows()

C++

1Mat img = imread("test.jpg");
2
3//Print the height and width of the image
4cout << "Width : " << img.size().width << endl;
5cout << "Height: " << img.size().height << endl;
6cout << "Channels: " << img.channels() << endl;
7
8// Display image
9imshow("Image", img);
10waitKey(0);
11destroyAllWindows();

上面的代码读取并显示图像及其尺寸。维度不仅包括二维矩阵的宽度和高度,还包括通道数(例如,RGB 图像有 3 个通道——红色、绿色和蓝色)。

让我们尝试裁剪包含花朵的图像部分。

Python

1cropped_image = img[80:280150:330# Slicing to crop the image
2
3# Display the cropped image
4cv2.imshow("cropped", cropped_image)
5cv2.waitKey(0)
6cv2.destroyAllWindows()

C++

1Mat crop = img(Range(80,280),Range(150,330)); // Slicing to crop the image
2
3// Display the cropped image
4imshow("Cropped Image", crop);
5
6waitKey(0);
7destroyAllWindows();
8return 0;


image.png


在 Python 中,您使用与 NumPy 数组切片相同的方法裁剪图像。要对数组进行切片,您需要指定第一维和第二维的开始和结束索引。 

  • 第一个维度始终是图像的行数或高度。

  • 第二个维度是图像的列数或宽度。 

二维数组的第一个维度表示数组的行(其中每一行表示图像的 y 坐标),这符合惯例。如何对 NumPy 数组进行切片?查看此示例中的语法:

cropped = img[start_row:end_row, start_col:end_col]

在 C++ 中,我们使用该Range()函数来裁剪图像。 

  • 与 Python 一样,它也适用于切片。 

  • 在这里,图像也被读取为 2D 矩阵,遵循上述相同的约定。 

以下是裁剪图像的 C++ 语法:

img(Range(start_row, end_row), Range(start_col, end_col))

使用裁剪将图像分成小块

OpenCV 中裁剪的一种实际应用是将图像分割成更小的块。使用循环从图像中裁剪出一个片段。首先从图像的形状中获取所需补丁的高度和宽度。

Python

1img =  cv2.imread("test_cropped.jpg")
2image_copy = img.copy()
3imgheight=img.shape[0]
4imgwidth=img.shape[1]

C++

1Mat img = imread("test_cropped.jpg");
2Mat image_copy = img.clone();
3int imgheight = img.rows;
4int imgwidth = img.cols;

加载高度和宽度以指定需要裁剪较小补丁的范围。为此,请使用range()Python 中的函数。for现在,使用两个循环进行裁剪:

  1. 一个用于宽度范围

  2. 其他为高度范围 

我们使用高度和宽度分别为 76 像素和 104 像素的补丁。内部和外部循环的步幅(我们在图像中移动的像素数)等于我们正在考虑的补丁的宽度和高度。

Python

1= 76
2= 104
3x1 = 0
4y1 = 0
5
6for in range(0, imgheight, M):
7    for in range(0, imgwidth, N):
8        if (imgheight - y) < M or (imgwidth - x) < N:
9            break
10
11        y1 = + M
12        x1 = + N
13
14        # check whether the patch width or height exceeds the image width or height
15        if x1 >= imgwidth and y1 >= imgheight:
16            x1 = imgwidth - 1
17            y1 = imgheight - 1
18            #Crop into patches of size MxN
19            tiles = image_copy[y:y+M, x:x+N]
20            #Save each patch into file directory
21            cv2.imwrite('saved_patches/'+'tile'+str(x)+'_'+str(y)+'.jpg', tiles)
22            cv2.rectangle(img, (x, y), (x1, y1), (02550), 1)
23        elif y1 >= imgheight: # when patch height exceeds the image height
24            y1 = imgheight - 1
25            #Crop into patches of size MxN
26            tiles = image_copy[y:y+M, x:x+N]
27            #Save each patch into file directory
28            cv2.imwrite('saved_patches/'+'tile'+str(x)+'_'+str(y)+'.jpg', tiles)
29            cv2.rectangle(img, (x, y), (x1, y1), (02550), 1)
30        elif x1 >= imgwidth: # when patch width exceeds the image width
31            x1 = imgwidth - 1
32            #Crop into patches of size MxN
33            tiles = image_copy[y:y+M, x:x+N]
34            #Save each patch into file directory
35            cv2.imwrite('saved_patches/'+'tile'+str(x)+'_'+str(y)+'.jpg', tiles)
36            cv2.rectangle(img, (x, y), (x1, y1), (02550), 1)
37        else:
38            #Crop into patches of size MxN
39            tiles = image_copy[y:y+M, x:x+N]
40            #Save each patch into file directory
41            cv2.imwrite('saved_patches/'+'tile'+str(x)+'_'+str(y)+'.jpg', tiles)
42            cv2.rectangle(img, (x, y), (x1, y1), (02550), 1)

C++

1int M = 76;
2int N = 104;
3
4int x1 = 0;
5int y1 = 0;
6for (int y = 0; y<imgheight; y=y+M)
7{
8    for (int x = 0; x<imgwidth; x=x+N)
9    {
10        if ((imgheight - y) < M || (imgwidth - x) < N)
11        {
12            break;
13        }
14        y1 = y + M;
15        x1 = x + N;
16        string a = to_string(x);
17        string b = to_string(y);
18
19        if (x1 >= imgwidth && y1 >= imgheight)
20        {
21            x = imgwidth - 1;
22            y = imgheight - 1;
23            x1 = imgwidth - 1;
24            y1 = imgheight - 1;
25
26            // crop the patches of size MxN
27            Mat tiles = image_copy(Range(y, imgheight), Range(x, imgwidth));
28            //save each patches into file directory
29            imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles); 
30            rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);   
31        }
32        else if (y1 >= imgheight)
33        {
34            y = imgheight - 1;
35            y1 = imgheight - 1;
36
37            // crop the patches of size MxN
38            Mat tiles = image_copy(Range(y, imgheight), Range(x, x+N));
39            //save each patches into file directory
40            imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles); 
41            rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);   
42        }
43        else if (x1 >= imgwidth)
44        {
45            x = imgwidth - 1;  
46            x1 = imgwidth - 1;
47
48            // crop the patches of size MxN
49            Mat tiles = image_copy(Range(y, y+M), Range(x, imgwidth));
50            //save each patches into file directory
51            imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles); 
52            rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);   
53        }
54        else
55        {
56            // crop the patches of size MxN
57            Mat tiles = image_copy(Range(y, y+M), Range(x, x+N));
58            //save each patches into file directory
59            imwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles); 
60            rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);   
61        }
62    }
63}

接下来,使用该imshow()函数显示图像补丁。imwrite()使用函数 将其保存到文件目录中。

Python

1#Save full image into file directory
2cv2.imshow("Patched Image",img)
3cv2.imwrite("patched.jpg",img)
4
5cv2.waitKey()
6cv2.destroyAllWindows()

C++

1imshow("Patched Image", img);
2imwrite("patched.jpg",img);
3waitKey();
4destroyAllWindows();


上面覆盖有矩形补丁的最终图像将如下所示: 

image.png


下图显示了保存到磁盘的单独图像补丁。

image.png


立即咨询
  • 品质服务

    服务贴心周到

  • 快速响应

    全天24小时随时沟通

  • 专业服务

    授权率高,保密性强

  • 完善售后服务

    快速响应需求,及时性服务

直播课程
软件开发基础课程
上位机软件开发课
机器视觉软件开发课
专题课
联系方式
电话:15861139266
邮箱:75607802@qq.com
地址:苏州吴中区木渎镇尧峰路69号
关注我们

版权所有:大林机器视觉培训苏州办事处所有 备案号:苏ICP备14016686号-6

技术支持: 新易维软件