Python OpenCV 方法 | cv2.putText()

| | | | | | | | | | | | | | | |

OpenCV Python 是一個 Python 鏈接庫,旨在解決計算機視覺問題。 cv2.putText () 方法用於在任意圖像上繪製文本字符串。

cv2 puttext

< td class="paramname">lineType = LINE_8,
void cv::putText ( InputOutputArray  img,
const String &  文本,
點  org ,
int  fontFace,
雙  fontScale,
< /td> 標量  顏色,
int  厚度 = 1 ,
int 
bool  bottomLeftOrigin = false 
)

語法:cv2.putText(image, text, org, font, fontScale, color[, thickness[, lineType[, bottomLeftOrigin]]]) 參數:image :要在其上繪製文本的圖像。

text:要繪製的文本字符串。

org:圖片中文本字符串左下角的坐標。坐標表示為兩個值的元組,即(X坐標值,Y坐標值)。

字體:表示字體類型。一些字體類型為 FONT_HERSHEY_SIMPLEX、FONT_HERSHEY_PLAIN 等。

fontScale:字體比例因子乘以特定字體的基本大小。

color:要繪製的文本字符串的顏色。對於 BGR,我們傳遞一個元組。 eg: (255, 0, 0) 表示藍色。

thickness:以px為單位的線條粗細。

lineType:這是一個可選參數。它給出了要使用的線的類型。

bottomLeftOrigin:這是一個可選參數。為真時,圖像數據原點位於左下角。否則,它在左上角。

返回值:它返回一個圖像。


如何使用 Python OpenCV2 在 windows 中的圖像上寫文字?

StackOverflow 問題

我想在上面放一些文字一個圖像。我將代碼編寫為:

cv2.putText(image,"Hello World!!!", (x,y), cv2.CV_FONT_HERSHEY_SIMPLEX, 2, 255) 

它給出錯誤,說`模塊`對像沒有屬性`CV_FONT_HERSHEY_SIMPLEX`

查詢可以` t 我使用上述字體類型?我在互聯網上搜索,但只找到與 Opencv C++ 相關的 initFont 語法。然後我想到了使用 putText 將字體類型作為參數傳遞。但它對我不起作用。

有什麼建議嗎?

答案:

此代碼使用 cv2.putText 在圖像上覆蓋文本。您需要安裝 NumPy 和 OpenCV。

import

span> numpy as np import cv2 # 創建黑色圖像 img = np.zeros((512,512,3), np.uint8) # 寫一些文字 font = cv2.FONT_HERSHEY_SIMPLEX bottomLeftCornerOfText = ( 10,500) fontScale = 1 fontColor = (255,255,255) lineType = 2 cv2.putText(img,`Hello World!`, bottomLeftCornerOfText, font, fontScale, fontColor, lineType) #顯示圖片 cv2.imshow("img",img) #Save image cv2.imwrite ("out.jpg", img) cv2.waitKey(0)

使用Python cv2.puttext在圖片中心寫文字

如果你知道你在圖片上寫的文字的形狀(寬,高),你可以把它放在中心在圖像上對齊。

上例中文本的大致形狀為 (268, 36)。您可能需要使用 Paint 或其他應用程序查找特定文本的形狀。

import numpy as np import cv2 image = cv2.imread(`sample.png`,cv2.IMREAD_UNCHANGED) position = ( (int) (image.shape[1]/2 - 268/2), (int) (image.shape[0]/2 - 36/2)) cv2.putText( image, #numpy array 寫入文本“Python 示例”,#text 位置,必須開始書寫的#position cv2.FONT_HERSHEY_SIMPLEX,#font family 1,#font size (209, 80, 0, 255),#font color 3) #font stroke cv2.imwrite (`output.png`, image) 

輸出圖片:

cv2 puttext

Python OpenCV puttext




cv2 putte xt Example #

def detect(imgfile): origimg = cv2.imread(imgfile) img = preprocess(origimg) img = img.astype(np.float32) img = img.transpose((2, 0 , 1)) net.blobs[`data`].data[...] = img out = net.forward() box, conf, cls = postprocess(origimg, out) for i in range(len(box)) : p1 = (box[i][0], box[i][1]) p2 = (box[i][2], box[i][3]) cv2.rectangle(origimg, p1, p2, ( 0,255,0)) p3 = (max(p1[0], 15), max(p1[1], 15)) 標題 = "%s:%.2f" % (COCO_CLASSES[int(cls[i])] , conf[i]) cv2.putText(origimg, title, p3, cv2.FONT_ITALIC, 0.6, (0, 255, 0), 1) cv2.imshow("SSD", origimg) k = cv2.waitKey(0) & 0xff #Exit if ESC press if k == 27: return False return True 

cv2.puttext Example #

def drawBoundingBox(self,imgcv,result): for box in result : # print(box) x1,y1,x2,y2 = (box[`topleft`][`x`],box[`topleft`][`y`],box[`bottomright`][`x`] ,box[`bottomright`][`y`]) conf = box[`confidence`] # print(conf) label = box[`label`] if conf < self.predictThresh: continue # print(x1,y1,x2 ,y2,conf, label) cv2.rectangle(imgcv,(x1,y1),(x2,y2),(0,255,0),6) labelSize=cv2.getTextSize(label,cv2.FONT_HERSHEY_COMPLEX,0.5,2) # print(`labelSize> >`,labelSize) _x1 = x1 _y1 = y1#+int(labelSize[0][1]/2) _x2 = _x1+labelSize[0][0] _y2 = y1-int(labelSize[0][1]) cv2.rectangle(imgcv,(_x1,_y1),(_x2,_y2),(0,255,0),cv2.FILLED) cv2.putText(imgcv,label,(x1,y1),cv2.FONT_HERSHEY_COMPLEX,0.5,(0 ,0,0),1) return imgcv 

cv2 puttext Example #

def draw_labels(x, y, class_names=None): img = x.numpy() if img. ndim == 2 或 img.shape[2] == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) 盒子, classes = tf.split(y, (4, 1), axis=-1) classes = classes[..., 0] wh = np.flip(img.shape[0:2]) min_wh = np.amin(wh) if min_wh <= 100: font_size = 0.5 else: font_size = 1 for i in range( len(boxes)): x1y1 = tuple((np.array(boxes[i][0:2]) * wh).astype(np.int32)) x2y2 = tuple((np.array(boxes[i][ 2:4]) * wh).astype(np.int32)) img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1) if class_names: img = cv2.putText(img, class_names[classes[i]], x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size, (0, 0, 255), 1) else: img = cv2.putText(img, str(classes[i]), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, 1, (0, 0, 255), 1) return img 

cv2.puttext Example #

def draw_outputs(img, outputs, class_names=None): box, objectness, classes = 輸出 #boxes, objectness, classes = boxes[0], objectness[0], classes[0] wh = np.flip(img.shape[0:2]) if img.ndim == 2 or img.shape[ 2] == 1: img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR) min_wh = np.amin(wh) 如果 min_wh <= 100: font_size = 0.5 else: font_size = 1 for i in range(classes.shape[0 ]): x1y1 = 元組((np.array(boxes[i][0:2]) * wh).astype(np.int32)) x2y2 = 元組((np.array(boxes[i][2:4 ]) * wh).astype(np.int32)) img = cv2.rectangle(img, x1y1, x2y2, (255, 0, 0), 1) img = cv2.putText(img, `{}`.format( int(classes[i])), x1y1, cv2.FONT_HERSHEY_COMPLEX_SMALL, font_size, (0, 0, 255), 1) return img 

cv2 puttext Example #

def detect( imgfile): 原始文件= cv2.imread(imgfile) img = preprocess(origimg) img = img.astype(np.float32) img = img.transpose((2, 0, 1)) net.blobs[`data`].data[.. .] = img out = net.forward() box, conf, cls = postprocess(origimg, out) for i in range(len(box)): p1 = (box[i][0], box[i][ 1]) p2 = (box[i][2], box[i][3]) cv2.rectangle(origimg, p1, p2, (0,255,0)) p3 = (max(p1[0], 15) , max(p1[1], 15)) title = "%s:%.2f" % (CLASSES[int(cls[i])], conf[i]) cv2.putText(origimg, title, p3, cv2 .FONT_ITALIC, 0.6, (0, 255, 0), 1) cv2.imshow("SSD", origimg) k = cv2.waitKey(0) & 0xff #Exit if ESC press if k == 27: return False return True 

cv2.puttext Example #

def draw_boxes_frame(frame, frame_size, boxes_dicts, class_names, input_size): """在視頻幀中繪製檢測到的框""" boxes_dict = boxes_dicts[ 0] resize_factor = (frame_size[0] / input_size[1], frame_size[1] / input_size[0]) for cls in range(len(class_names)): boxes = boxes_dict[cls] color = (0, 0, 255 ) 如果 np.size(boxes) != 0:對於盒子中的盒子:xy = box[:4] xy = [int(xy[i] * resize_factor[i % 2]) for i in range(4)] cv2.rectangle(frame, (xy[0], xy[1]), (xy [2], xy[3]), 顏色[::-1], 2) (test_width, text_height), 基線 = cv2.getTextSize(class_names[cls], cv2.FONT_HERSHEY_SIMPLEX, 0.75, 1) cv2.rectangle(frame , (xy[0], xy[1]), (xy[0] + test_width, xy[1] - text_height - 基線), color[::-1],粗細=cv2.FILLED) cv2.putText(frame , class_names[cls], (xy[0], xy[1] - baseline), cv2.FONT_HERSHEY_SIMPLEX, 0.75, (0, 0, 0), 1) 

cv2 puttext Example #

def ProcessFrame(self, frame): # 分割手臂區域 segment = self.SegmentArm(frame) # 複製分割後的圖像在 draw = cv2.cvtColor(segment, cv2.COLOR_GRAY2RGB) # 繪製一些幫助正確放置手 cv2.circle(draw,(self.imgWidth/2,self.imgHeight/2),3,[255,102,0],2) cv2.rectangle(draw, (self.imgWidth/3,self. imgHeight/3), (self.imgWidth*2/3, self.imgHeight*2/3), [255,102,0],2) # 找到分割區域的外殼,並在此基礎上找到 # c onvexity 缺陷 [contours,defects] = self.FindHullDefects(segment) # 根據輪廓和凸度缺陷檢測手指的數量 # 將屬於手指的缺陷繪製為綠色,其他為紅色 [nofingers,draw] = self.DetectNumberFingers(contours,缺陷, 繪製) # 在圖像上打印手指數 cv2.putText(draw, str(nofingers), (30,30), cv2.FONT_HERSHEY_SIMPLEX, 1, (255,255,255)) return draw 

cv2.puttext Example #

def vis_class(img, pos, class_str, bg_color): """可視化類。""" font_color = cfg.VIS.SHOW_CLASS.COLOR font_scale = cfg.VIS.SHOW_CLASS.FONT_SCALE x0 , y0 = int(pos[0]), int(pos[1]) # 計算文本大小。 txt = class_str font = cv2.FONT_HERSHEY_SIMPLEX ((txt_w, txt_h), _) = cv2.getTextSize(txt, font, font_scale, 1) # 放置文字背景。 back_tl = x0, y0 - int(1.3 * txt_h) back_br = x0 + txt_w, y0 cv2.rectangle(img, back_tl, back_br, bg_color, -1) # 顯示文本。txt_tl = x0, y0 - int(0.3 * txt_h) cv2.putText(img, txt, txt_tl, font, font_scale, font_color, lineType=cv2.LINE_AA) return img 

cv2 puttext Example #

def plot_one_box(x, img, color=None, label=None, line_thickness=None): # 在圖像上繪製一個邊界框 img tl = line_thickness or round(0.002 * (img.shape[0] + img. shape[1]) / 2) + 1 # 線條粗細 color = color or [random.randint(0, 255) for _ in range(3)] c1, c2 = (int(x[0]), int(x [1])), (int(x[2]), int(x[3])) cv2.rectangle(img, c1, c2, color, thickness=tl) if label: tf = max(tl - 1, 1) # 字體粗細 t_size = cv2.getTextSize(label, 0, fontScale=tl / 3,粗細=tf)[0] c2 = c1[0] + t_size[0], c1[1] - t_size[1] - 3 cv2.rectangle(img, c1, c2, color, -1) # 填充 cv2.putText(img, label, (c1[0], c1[1] - 2), 0, tl / 3, [225, 255 , 255], 厚度=tf, lineType=cv2.LINE_AA) 

cv2.puttext 示例#

def vis_det_and_mask(im, class_name, dets, mask, thresh=0.8): " ""檢測的可視化調試。""" n um_dets = np.minimum(10, dets.shape[0]) colors_mask = random_colors(num_dets) colors_bbox = np.round(np.random.rand(num_dets, 3) * 255) # 根據坐標排序rois,繪製上bbox first draw_mask = np.zeros(im.shape[:2], dtype=np.uint8) for i in range(1): bbox = tuple(int(np.round(x)) for x in dets[i, :4]) mask = mask[i,:,:] full_mask = unmold_mask(mask, bbox, im.shape) score = dets[i, -1] if score > thresh: word_width = len(class_name) cv2.rectangle( im, bbox[0:2], bbox[2:4], colors_bbox[i], 2) cv2.rectangle(im, bbox[0:2], (bbox[0] + 18 + word_width*8, bbox[ 1]+15),colors_bbox[i],粗細=cv2.FILLED) apply_mask(im, full_mask, draw_mask, colors_mask[i], 0.5) draw_mask += full_mask cv2.putText(im, `%s` % (class_name) , (bbox[0]+5, bbox[1] + 12), cv2.FONT_HERSHEY_PLAIN, 1.0, (255,255,255), 厚度=1) 返回 im 

我們希望本文能幫助您解決問題。 除了 Python OpenCV 方法 | cv2.putText(),查看其他與 __del__ 相關的主題。

想在 Python 中出類拔萃? 查看我們對 最佳 Python 在線課程 2022的評論。 如果您對數據科學感興趣,請查看如何學習 R 編程

順便說一句,此材料也有其他語言版本:



Ken Lehnman

Munchen | 2022-11-29

谢谢你的解释! 我被Python OpenCV 方法 | cv2.putText()卡住了几个小时。了几个小时,最后终于完成了 🤗. 明天會回來反饋

Olivia Gonzalez

Paris | 2022-11-29

也许有其他的答案?什么是Python OpenCV 方法 | cv2.putText()?到底是什么意思?. 我只是不太確定這是最好的方法

Olivia Richtgofen

Warsaw | 2022-11-29

简单地说,很清楚。谢谢你的分享。Python OpenCV 方法 | cv2.putText()和其他问题的find一直是我的弱点😁。. 明天會回來反饋

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

Common xlabel/ylabel for matplotlib subplots

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

12 answers

NUMPYNUMPY

Flake8: Ignore specific warning for entire file

12 answers

NUMPYNUMPY

glob exclude pattern

12 answers

NUMPYNUMPY

How to avoid HTTP error 429 (Too Many Requests) python

12 answers

NUMPYNUMPY

Python CSV error: line contains NULL byte

12 answers

NUMPYNUMPY

csv.Error: iterator should return strings, not bytes

12 answers

News


Wiki

Python | How to copy data from one Excel sheet to another

Common xlabel/ylabel for matplotlib subplots

Check if one list is a subset of another in Python

sin

How to specify multiple return types using type-hints

exp

Printing words vertically in Python

exp

Python Extract words from a given string

Cyclic redundancy check in Python

Finding mean, median, mode in Python without libraries

cos

Python add suffix / add prefix to strings in a list

Why do I get "Pickle - EOFError: Ran out of input" reading an empty file?

Python - Move item to the end of the list

Python - Print list vertically