回答編集履歴
4
d
answer
CHANGED
@@ -8,4 +8,39 @@
|
|
8
8
|
矩形描画も Pillow でできるので、描画は Pillow に統一して、PIL.Image.save() で画像を保存するようにしてはどうでしょうか
|
9
9
|
矩形描画やテキストの大きさ取得等も Pillow に同等の機能の関数があります。
|
10
10
|
|
11
|
-
[ImageDraw Module — Pillow (PIL Fork) 7.2.0 documentation](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html)
|
11
|
+
[ImageDraw Module — Pillow (PIL Fork) 7.2.0 documentation](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html)
|
12
|
+
|
13
|
+
## 追記
|
14
|
+
|
15
|
+
```python
|
16
|
+
import cv2
|
17
|
+
from PIL import Image, ImageDraw, ImageFont
|
18
|
+
|
19
|
+
|
20
|
+
def draw_text_with_box(img, origin, text, fontsize=20, color="red"):
|
21
|
+
# フォントを作成する。
|
22
|
+
font = ImageFont.truetype("ipag.ttc", size=fontsize) # 使用フォントは変更してください
|
23
|
+
|
24
|
+
draw = ImageDraw.Draw(img, mode="RGBA")
|
25
|
+
|
26
|
+
# テキストの大きさを取得する。
|
27
|
+
size = draw.textsize(text, font=font)
|
28
|
+
# テキストを囲む矩形を描画する。
|
29
|
+
draw.rectangle(
|
30
|
+
(origin, (origin[0] + size[0] - 1, origin[1] + size[1] - 1)),
|
31
|
+
outline="black",
|
32
|
+
width=2,
|
33
|
+
)
|
34
|
+
# テキストを描画する。。
|
35
|
+
draw.text(origin, text, fill=color, font=font)
|
36
|
+
|
37
|
+
|
38
|
+
img = cv2.imread("sample.png")
|
39
|
+
img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB)) # RGB に並び替え必要
|
40
|
+
|
41
|
+
draw_text_with_box(img, (30, 30), "にわとり", color="blue", fontsize=30)
|
42
|
+
|
43
|
+
img.save("ret.png")
|
44
|
+
```
|
45
|
+
|
46
|
+

|
3
d
answer
CHANGED
File without changes
|
2
d
answer
CHANGED
@@ -6,6 +6,6 @@
|
|
6
6
|
なので、`cv2.rectangle()` で `img` のほうに矩形を描画し、Pillow で `image` にテキストを描画して、`img` のほうを保存したとしても Pillow で描画したテキストは反映されていない状態になります。
|
7
7
|
|
8
8
|
矩形描画も Pillow でできるので、描画は Pillow に統一して、PIL.Image.save() で画像を保存するようにしてはどうでしょうか
|
9
|
-
テキストの大きさ取得等も Pillow に同等
|
9
|
+
矩形描画やテキストの大きさ取得等も Pillow に同等の機能の関数があります。
|
10
10
|
|
11
11
|
[ImageDraw Module — Pillow (PIL Fork) 7.2.0 documentation](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html)
|
1
d
answer
CHANGED
@@ -6,5 +6,6 @@
|
|
6
6
|
なので、`cv2.rectangle()` で `img` のほうに矩形を描画し、Pillow で `image` にテキストを描画して、`img` のほうを保存したとしても Pillow で描画したテキストは反映されていない状態になります。
|
7
7
|
|
8
8
|
矩形描画も Pillow でできるので、描画は Pillow に統一して、PIL.Image.save() で画像を保存するようにしてはどうでしょうか
|
9
|
+
テキストの大きさ取得等も Pillow に同等に機能の関数があります。
|
9
10
|
|
10
11
|
[ImageDraw Module — Pillow (PIL Fork) 7.2.0 documentation](https://pillow.readthedocs.io/en/stable/reference/ImageDraw.html)
|