MCPcopy Create free account
hub / github.com/YesianRohn/TextSSR / draw_glyph

Method draw_glyph

anyword_data.py:173–199  ·  view source on GitHub ↗
(self, text, rect, font_path="AlibabaPuHuiTi-3-85-Bold.ttf")

Source from the content-addressed store, hash-verified

171 return img_tensor
172
173 def draw_glyph(self, text, rect, font_path="AlibabaPuHuiTi-3-85-Bold.ttf"):
174 resolution = self.resolution
175 # Create a 3-channel (RGB) background image initialized to white
176 bg_img = np.ones((resolution, resolution, 3), dtype=np.uint8) * 255
177 font = ImageFont.truetype(font_path, self.ttf_size)
178 text_img = Image.new('RGB', font.getsize(text), (255, 255, 255)) # Create an RGB image initialized to white
179 draw = ImageDraw.Draw(text_img)
180 draw.text((0, 0), text, font=font, fill=(127, 127, 127)) # Draw text in gray
181 text_np = np.array(text_img)
182 rec_h, rec_w = rect[1]
183 box = cv2.boxPoints(rect)
184 if rec_h > rec_w * 1.5:
185 box = [box[1], box[2], box[3], box[0]]
186 dst_points = np.array(box, dtype=np.float32)
187 src_points = np.float32([[0, 0], [text_np.shape[1], 0], [text_np.shape[1], text_np.shape[0]], [0, text_np.shape[0]]])
188 M = cv2.getPerspectiveTransform(src_points, dst_points)
189 warped_text_img = cv2.warpPerspective(text_np, M, (resolution, resolution))
190 # Create a mask where the text is non-white (non-background)
191 mask = np.any(warped_text_img == [127, 127, 127], axis=-1)
192 # Use the mask to overlay the warped_text_img onto the bg_img
193 bg_img[mask] = warped_text_img[mask]
194 # Convert the final image to a tensor
195 # Convert to float and scale to [0, 1]
196 bg_img = bg_img.astype(np.float32) / 255.0
197 # Convert to PyTorch tensor
198 bg_img_tensor = torch.from_numpy(bg_img).permute(2, 0, 1) # Change from HWC to CHW format
199 return bg_img_tensor

Callers 1

__getitem__Method · 0.95

Calls

no outgoing calls

Tested by

no test coverage detected