teratail header banner
teratail header banner
質問するログイン新規登録

回答編集履歴

1

d

2020/09/15 05:53

投稿

tiitoi
tiitoi

スコア21960

answer CHANGED
@@ -12,4 +12,50 @@
12
12
  ```
13
13
 
14
14
 
15
- [OpenCV - 画像を切り抜く、チャンネルを分離、結合する方法 - pystyle](https://pystyle.info/opencv-ndarray-manipulation/#outline__3)
15
+ [OpenCV - 画像を切り抜く、チャンネルを分離、結合する方法 - pystyle](https://pystyle.info/opencv-ndarray-manipulation/#outline__3)
16
+
17
+ ## 追記
18
+
19
+ ```python
20
+ import cv2
21
+
22
+
23
+ cascade_path = "haarcascade_frontalface_alt.xml"
24
+ # カスケード分類器の特徴量取得
25
+ cascade = cv2.CascadeClassifier(cascade_path)
26
+
27
+
28
+ # 画像を読み込む。
29
+ img = cv2.imread("image.jpg")
30
+
31
+ # グレースケールに変換する。
32
+ grayscale_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
33
+
34
+ # 検出する。
35
+ faces = cascade.detectMultiScale(grayscale_img, minSize=(100, 100))
36
+
37
+
38
+ def crop_and_save(path, img, tl, br):
39
+ """矩形 (tr, br) の範囲を切り抜く。
40
+ """
41
+ cropped = img[tl[1] : br[1], tl[0] : br[0]]
42
+
43
+ cv2.imwrite(path, cropped)
44
+
45
+
46
+ # 矩形を画像に描画する。
47
+ for x, y, w, h in faces:
48
+ cv2.rectangle(img, (x, y), (x + w, y + h), color=(0, 255, 0), thickness=10)
49
+
50
+ tl = 516 - 113, 123 + 113 # 上半身の左上の座標
51
+ br = 516 + 1 * 113, 123 + 113 * 4 # 上半身の右下の座標
52
+ crop_and_save("upper.jpg", img, tl, br)
53
+ #cv2.rectangle(img, tl, br, color=(0, 0, 255), thickness=10)
54
+
55
+ tl1 = 516 - 113, 123 + 113 * 4 # 上半身の左上の座標
56
+ br1 = 516 + 1 * 113, 123 + 113 * 10 # 上半身の右下の座標
57
+ crop_and_save("lower.jpg", img, tl1, br1)
58
+ #cv2.rectangle(img, tl1, br1, color=(0, 0, 255), thickness=10)
59
+
60
+ #cv2.imwrite("out3.jpg", img)
61
+ ```