@@ -412,38 +412,6 @@ img.show()
412412
413413## 图像运算
414414
415- ### 图像截取
416-
417- 图像的本质是数组,所以图像的截取就是数组的截取。
418-
419- ``` python showLineNumbers
420- img = cv2.imread(" demo.jpg" )
421-
422- # 1. 知道左上角 + 宽高(最常用)
423- x, y, w, h = 100 , 200 , 300 , 400
424- cropped = img[y:y+ h, x:x+ w]
425-
426- # 2. 知道左上角和右下角坐标
427- x1, y1 = 100 , 200
428- x2, y2 = 400 , 600
429- cropped = img[y1:y2, x1:x2]
430-
431- # 3. 知道中心点 + 宽高(比如 YOLO 检测框)
432- center_x, center_y = 320 , 240
433- w, h = 200 , 300
434- x = int (center_x - w/ 2 )
435- y = int (center_y - h/ 2 )
436- cropped = img[y:y+ h, x:x+ w]
437-
438- # 4. 防止越界(生产必加,防止 crash)
439- h_img, w_img = img.shape[:2 ]
440- x = max (0 , x)
441- y = max (0 , y)
442- w = min (w, w_img - x)
443- h = min (h, h_img - y)
444- cropped = img[y:y+ h, x:x+ w]
445- ```
446-
447415加减法的前提是两张图片的尺寸相同。
448416
449417### 图像加法、图像减法
@@ -694,23 +662,38 @@ img = cv2.imread("xxx.png")
694662# 获取图像尺寸
695663height, width = img.shape[:2 ]
696664
697- # 裁剪中心区域(从坐标(100,100)到(300,300))
698- cropped_img = img[100 :300 , 100 :300 ]
699-
700665# 裁剪图像上半部分
701666top_half = img[0 :height// 2 , 0 :width]
702667
703668# 裁剪图像右下角四分之一
704669bottom_right = img[height// 2 :height, width// 2 :width]
705670
706- cv2.imshow(" Original" , img)
707- cv2.imshow(" Cropped" , cropped_img)
708- cv2.imshow(" Top Half" , top_half)
709- cv2.imshow(" Bottom Right" , bottom_right)
710- cv2.waitKey(0 )
711- cv2.destroyAllWindows()
671+ # 知道左上角 + 宽高
672+ x, y, w, h = 100 , 200 , 300 , 400
673+ cropped = img[y:y+ h, x:x+ w]
674+
675+ # 知道左上角和右下角坐标
676+ x1, y1 = 100 , 200
677+ x2, y2 = 400 , 600
678+ cropped = img[y1:y2, x1:x2]
679+
680+ # 知道中心点 + 宽高(比如 YOLO 检测框)
681+ center_x, center_y = 320 , 240
682+ w, h = 200 , 300
683+ x = int (center_x - w/ 2 )
684+ y = int (center_y - h/ 2 )
685+ cropped = img[y:y+ h, x:x+ w]
686+
687+ # 防止越界(生产必加,防止 crash)
688+ h_img, w_img = img.shape[:2 ]
689+ x = max (0 , x)
690+ y = max (0 , y)
691+ w = min (w, w_img - x)
692+ h = min (h, h_img - y)
693+ cropped = img[y:y+ h, x:x+ w]
712694```
713695
696+
714697### 图像平移
715698
716699函数签名:` cv2.warpAffine(src, M, dsize, flags, borderMode, borderValue) -> dst `
0 commit comments