裁剪是为了从图像中删除所有不需要的物体或区域。甚至突出显示图像的特定功能。

使用OpenCV裁剪没有特定的功能,NumPy数组切片是工作。读取的每个图像都存储在2D数组中(对于每个颜色通道)。只需指定要裁剪区域的高度和宽度(以像素为单位),就可以完成

使用OpenCV裁剪图像

  • 1.使用OpenCV裁剪
  • 2.使用裁剪功能对图像进行划分

1.使用OpenCV裁剪

以下代码片段展示了如何使用Python和C++裁剪图像。在例子的进一步,您将详细了解这些。
Python

# Import packages
import cv2
import numpy as npimg = cv2.imread('test.jpg')
print(img.shape) # Print image shape
cv2.imshow("original", img)# Cropping an image
cropped_image = img[400:1200, 350:700]# Display cropped image
cv2.imshow("cropped", cropped_image)# Save the cropped image
cv2.imwrite("Cropped Image.jpg", cropped_image)cv2.waitKey(0)
cv2.destroyAllWindows()

C++

// Include Libraries
#include<opencv2/opencv.hpp>
#include<iostream>// Namespace nullifies the use of cv::function();
using namespace std;
using namespace cv;int main()
{// Read imageMat img = imread("test.jpg");cout << "Width : " << img.size().width << endl;cout << "Height: " << img.size().height << endl;cout<<"Channels: :"<< img.channels() << endl;// Crop imageMat cropped_image = img(Range(400,1200), Range(350,700));//display imageimshow(" Original Image", img);imshow("Cropped Image", cropped_image);//Save the cropped Imageimwrite("Cropped Image.jpg", cropped_image);// 0 means loop infinitelywaitKey(0);destroyAllWindows();return 0;
}

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

让我们尝试裁剪图像中包含美女的部分。

Python

cropped_image = img[400:1200, 350:700] # Slicing to crop the image# Display the cropped image
cv2.imshow("cropped", cropped_image)
cv2.waitKey(0)
cv2.destroyAllWindows()

C++

Mat crop = img(Range(400,1200),Range(350,700)); // Slicing to crop the image// Display the cropped image
imshow("Cropped Image", crop);waitKey(0);
destroyAllWindows();
return 0;


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

  • 第一个维度总是行数或图像的高度。
  • 第二个维度是列数或图像的宽度。

如何剪切图像的NumPy数组?查看此示例中的语法:

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

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

  • Python同理一样,它也应用切片。
  • 在这里,图像也按照上述相同的约定作为二维矩阵读取。

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

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

2.使用裁剪功能对图像进行划分

在OpenCV中裁剪的一个实际应用可以是将图像划分为大小相同图像块。使用循环从图像中裁剪片段。首先从图像的形状中获取所需图像块的高度和宽度

Python

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

C++

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

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

  • 宽度范围
  • 高度范围

已知原图像瘩高度宽度为(1350,1080),我们使用的图像块的高度和宽度分别为(270,216)。内外循环的步幅(我们在图像中移动的像素数)也就是划分下来,有25个图像块。(拼图一样)

Python

M = 216
N = 270
x1 = 0
y1 = 0for y in range(0, imgheight, M):for x in range(0, imgwidth, N):if (imgheight - y) < M or (imgwidth - x) < N:breaky1 = y + Mx1 = x + N# check whether the patch width or height exceeds the image width or heightif x1 >= imgwidth and y1 >= imgheight:x1 = imgwidth - 1y1 = imgheight - 1# Crop into patches of size MxNtiles = image_copy[y:y + M, x:x + N]# Save each patch into file directorycv2.imwrite(str(x) + '_' + str(y) + '.jpg', tiles)cv2.rectangle(img, (x, y), (x1, y1), (0, 255, 0), 1)elif y1 >= imgheight:  # when patch height exceeds the image heighty1 = imgheight - 1# Crop into patches of size MxNtiles = image_copy[y:y + M, x:x + N]# Save each patch into file directorycv2.imwrite(str(x) + '_' + str(y) + '.jpg', tiles)cv2.rectangle(img, (x, y), (x1, y1), (0, 255, 0), 1)elif x1 >= imgwidth:  # when patch width exceeds the image widthx1 = imgwidth - 1# Crop into patches of size MxNtiles = image_copy[y:y + M, x:x + N]# Save each patch into file directorycv2.imwrite(str(x) + '_' + str(y) + '.jpg', tiles)cv2.rectangle(img, (x, y), (x1, y1), (0, 255, 0), 1)else:# Crop into patches of size MxNtiles = image_copy[y:y + M, x:x + N]# Save each patch into file directorycv2.imwrite(str(x) + '_' + str(y) + '.jpg', tiles)cv2.rectangle(img, (x, y), (x1, y1), (0, 255, 0), 1)

C++

int M = 216;
int N = 270;int x1 = 0;
int y1 = 0;
for (int y = 0; y<imgheight; y=y+M)
{for (int x = 0; x<imgwidth; x=x+N){if ((imgheight - y) < M || (imgwidth - x) < N){break;}y1 = y + M;x1 = x + N;string a = to_string(x);string b = to_string(y);if (x1 >= imgwidth && y1 >= imgheight){x = imgwidth - 1;y = imgheight - 1;x1 = imgwidth - 1;y1 = imgheight - 1;// crop the patches of size MxNMat tiles = image_copy(Range(y, imgheight), Range(x, imgwidth));//save each patches into file directoryimwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);  rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);    }else if (y1 >= imgheight){y = imgheight - 1;y1 = imgheight - 1;// crop the patches of size MxNMat tiles = image_copy(Range(y, imgheight), Range(x, x+N));//save each patches into file directoryimwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);  rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);    }else if (x1 >= imgwidth){x = imgwidth - 1;   x1 = imgwidth - 1;// crop the patches of size MxNMat tiles = image_copy(Range(y, y+M), Range(x, imgwidth));//save each patches into file directoryimwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);  rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);    }else{// crop the patches of size MxNMat tiles = image_copy(Range(y, y+M), Range(x, x+N));//save each patches into file directoryimwrite("saved_patches/tile" + a + '_' + b + ".jpg", tiles);  rectangle(img, Point(x,y), Point(x1,y1), Scalar(0,255,0), 1);    }}
}

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

Python

#Save full image into file directory
cv2.imshow("Patched Image",img)
cv2.imwrite("patched.jpg",img)cv2.waitKey()
cv2.destroyAllWindows()

C++

imshow("Patched Image", img);
imwrite("patched.jpg",img);
waitKey();
destroyAllWindows();

Python

C++

OpenCV入门(C++/Python)-使用OpenCV裁剪图像(四)相关推荐

  1. 使用Python和OpenCV捕获鼠标事件,并裁剪图像

    使用Python和OpenCV捕获鼠标事件,并裁剪图像 1. 效果图 2. 源码 参考 这篇博客将介绍如何使用Python和OpenCV捕获鼠标事件.还演示了如何快速裁剪和提取图像区域,这在为自己的自 ...

  2. 转载:【OpenCV入门教程之四】 ROI区域图像叠加初级图像混合 全剖析

    [OpenCV入门教程之四] ROI区域图像叠加&初级图像混合 全剖析 浅墨_毛星云 2014-03-10 12:48:05 157425 收藏 19 最后发布:2014-03-10 12:4 ...

  3. OpenCV入门基础操作(二)----图像像素的处理

    OpenCV入门基础操作(二)----图像像素的处理 像素处理 读取一个图像像素 修改像素值 代码案例 像素处理 读取一个图像像素 在读取图像的时候一般要用到如下的命令: 返回值=图像(位置参数), ...

  4. OpenCV入门 | 使用Python实现计算机视觉的第一步

    不久前,我为一个大学项目训练了一个目标检测模型,但说实话,除了它需要很多计算力以及需要长时间观察我的训练模型,我不记得其他太更多的东西了. 最近我对这些话题重拾了兴趣,我决定重新开始学习,但这一次我会 ...

  5. OpenCV学习笔记03:缩放裁剪图像与调整图像色调

    文章目录 一.缩放裁剪图像 (一)resize函数 (二)缩放图像 1.编写程序,实现功能 2.运行程序,查看结果 (三)裁剪图像 1.编写程序,实现功能 2.运行程序,查看结果 二.调整图像色调 ( ...

  6. 【OpenCV入门教程之一】 OpenCV 2.4.8 +VS2010的开发环境配置

    目录(?)[-] 因为读研期间的研究方向是图像处理所以浅墨这段时间闭门研究了很多OpenCV和图像处理相关的知识与内容眼看自己积累到一定的程度了于是决定开始开设这个OpenCV系列专栏总结自己所学也分 ...

  7. 【OpenCV入门学习--python】图像的矩Image Moments

    例子源于OpenCV官网–图像的矩 (https://docs.opencv.org/4.x/d0/d49/tutorial_moments.html) 使用OpenCV函数cv::moments: ...

  8. 【OpenCV入门学习--python】索贝尔算子Sobel operator提取边缘

    例子源于OpenCV官网手册(https://docs.opencv.org/4.x/d2/d2c/tutorial_sobel_derivatives.html) 使用OpenCV函数Sobel() ...

  9. 【OpenCV入门学习--python】Image Segmentation with Distance Transform and Watershed Algorithm图像分割

    例子源于OpenCV官网–基于距离变换和分水岭算法的图像分割 (https://docs.opencv.org/4.x/d2/dbd/tutorial_distance_transform.html) ...

  10. 【OpenCV入门学习--python】Anisotropic image segmentation by a gradient structure tensor

    例子源于OpenCV官网–基于梯度结构张量的各向异性图像分割 (https://docs.opencv.org/4.x/d4/d70/tutorial_anisotropic_image_segmen ...

最新文章

  1. android.view.InflateException: Binary XML file line #16: Binary XML file line #16: Error inflating
  2. STM32开发 -- 4G模块开发详解(2)
  3. 细胞培养中出现黑胶虫污染处理方法
  4. sublime text常用快捷键及多行光标批量操作教程
  5. 使用uploadify上传图片时返回“Cannot read property 'queueData' of undefined”
  6. 关于编程学习的一些思考 | 欢迎投稿
  7. 【算法导论33】跳跃表(Skip list)原理与java实现
  8. [HNOI 2014]道路堵塞
  9. proxool mysql 配置 useunicode_proxool + MySQL + servelt 的使用
  10. vmware vsphere出现“需要整合虚拟机磁盘”的告警处理方法(完整版)
  11. 替换空格python实现
  12. m3u8文件下载及合并
  13. 什么是Word2Vec?如何有效的表征文本的?
  14. SEH X64(3)
  15. 自己写php木马,自己写的php木马webshell扫描器
  16. 如何重命名WordPress WP内容目录
  17. 30款后台源码。是我见过最全的后台代码。。
  18. 网安之php开发第十三天
  19. Android 音频(Audio)架构
  20. PLC控制气缸,如何使用二位五通和三位五通控制电磁阀控制

热门文章

  1. springboot RedisTemplate 提示没有双引号序列化失败问题
  2. 2021-2027全球及中国特种机器人行业研究及十四五规划分析报告
  3. Fabric.js添加辅助线的方法
  4. 防火墙网络地址转换技术
  5. 我的webgl学习之路(一)
  6. 22款奔驰S400L升级原厂主动氛围灯,H17钢琴条纹饰板等,浪漫奢华
  7. html音乐播放器样式,html5扁平化mp3音乐播放器样式代码
  8. 深入理解拉格朗日乘子法(Lagrange Multiplier) 和KKT条件
  9. python点图_Python | 点图
  10. javaCSGO赛事管理系统springbootvueweb