def to_render(rect, ch, rot=0): rot = to_rad(rot) rot = (-1) * rot x = rect[0] y = rect[1] try: ctx.translate(Vector(x, y)) ctx.rotate(rot) ctx.set_source_colour(Colour.grey(1)) ctx.set_font_face(qah_face) ctx.set_font_size(text_size) ctx.show_glyphs(ch) # ctx.glyph_path(ch) # ctx.stroke() ctx.rotate(-rot) ctx.translate(Vector(-x, -y)) except: ef = open('errorFile.txt', 'a') st = 'X co-ordinate ' + str(x) + ', Y co-ordinate ' + str( y) + ', Angle ' + str(rot) ef.write(st) ef.close() return art_BB(ch, x, y, rot)
def check_dimensions_ok(dimensions, where = None) : "checks that the Vector dimensions is suitable as the dimensions of an image" \ " for Frei0r to operate on." width, height = Vector.from_tuple(dimensions).assert_isint() assert max_image_dimension >= width > 0 and max_image_dimension >= height > 0 and width % image_dimension_modulo == 0 and height % image_dimension_modulo == 0, \ "invalid image dimensions%s" % (lambda : "", lambda : " %s" % where)[where != None]() return \ Vector(width, height)
def curve_func(x): theta_ring = circle * nr_cycles * x theta_wheel = theta_ring * (ring_radius / wheel_radius + 1) wheel_pos = Vector(ring_radius + wheel_radius, 0).rotate(theta_ring + phase * circle) curve_pos = wheel_pos + Vector(wheel_radius * wheel_frac, 0).rotate(theta_wheel) return curve_pos
def get_Bound_Glyph(abc): # Setting Starting position of the first glyph glyph_pos = Vector(0, 0) # Resetting the buffer buf.reset() # adding string to buffer buf.add_str(abc) # Figuring out segmentation properties buf.guess_segment_properties() # Gernerating Shapes for the text in buffer using the font hb.shape(hb_font, buf) # Getting glyphs out of buffer (list format) glyphs, end_glyph_pos = buf.get_glyphs(glyph_pos) # Creating fontface qah_face = qah.FontFace.create_for_ft_face(ft_face) glyph_extents = (qah.Context.create_for_dummy().set_font_face( qah_face).set_font_size(text_size).glyph_extents(glyphs)) # Getting the bound of the [glyphs] figure_bounds = math.ceil(glyph_extents.bounds) # Returning glyph and the figure bound return (figure_bounds, glyphs)
def set_dpi(self, dpi=0): if isinstance(dpi, Real): rsvg.rsvg_handle_set_dpi(self._rsvgobj, dpi) elif isinstance(dpi, (Vector, tuple, list)): dpi = Vector.from_tuple(dpi) rsvg.rsvg_handle_set_dpi_x_y(self._rsvgobj, dpi.x, dpi.y) else: raise TypeError("dpi must be a Real or a Vector")
def get_position_sub(self, id): pos = RSVG.PositionData() success = rsvg.rsvg_handle_get_position_sub(self._rsvgobj, ct.byref(pos), id.encode()) if success: result = Vector(pos.width, pos.height) else: result = None #end if return \ result
def get_dimensions(self, id=None): dims = RSVG.DimensionData() if id != None: success = rsvg.rsvg_handle_get_dimensions_sub( self._rsvgobj, ct.byref(dims), id.encode()) else: rsvg.rsvg_handle_get_dimensions(self._rsvgobj, ct.byref(dims)) success = True #end if if success: result = Vector(dims.width, dims.height) else: result = None #end if return \ result
def art_BB(ch, x, y, rot): # creating new surface here surf = qah.ImageSurface.create(format=CAIRO.FORMAT_RGB24, dimensions=fsize) cnt = qah.Context.create(surf) cnt.translate(Vector(x, y)) cnt.rotate(rot) cnt.set_source_colour(Colour.grey(1)) cnt.set_font_face(qah_face) cnt.set_font_size(text_size) cnt.show_glyphs(ch) cnt.glyph_path(ch) cnt.stroke() img = pngB_to_np(surf.to_png_bytes()) bb = boundB(img[:, :, 1]) # plt.imshow(img[:,:,1]) return bb
def construct(self, dimensions, rearrange = True) : "constructs a new instance of this Plugin, from the given (qahirah.Vector-compatible)" \ " dimensions. rearrange indicates whether to rearrange R and B channels as" \ " necessary to agree with Cairo’s FORMAT_ARGB32 channel ordering." width, height = check_dimensions_ok(dimensions) instance = self._lib.f0r_construct(width, height) if instance == None : raise RuntimeError \ ( "failure constructing plugin instance for “%s”" % self._parent.info.name ) #end if return \ type(self).Instance \ ( instance = instance, parent = self, dimensions = Vector(width, height), rearrange = rearrange and self.info.colour_model.rearrange )
import harfbuzz as hb ft = qah.get_ft_lib() _text = "Kivy is Awesome !" _font = "DejaVu Serif" text_size = 50 label_font = \ (qah.Context.create_for_dummy() .set_font_face(qah.FontFace.create_for_pattern("DejaVu Serif")) .set_font_size(text_size / 2) ).scaled_font buf = hb.Buffer.create() line_pos = Vector(0, 0) ft_face = ft.find_face(_font) ft_face.set_char_size(size = text_size, resolution = qah.base_dpi) hb_font = hb.Font.ft_create(ft_face) buf.reset() buf.add_str(_text) buf.guess_segment_properties() hb.shape(hb_font, buf) line, line_end = buf.get_glyphs(line_pos) lines =\ { "font" : (qah.Context.create_for_dummy() .set_font_face(qah.FontFace.create_for_ft_face(ft_face)) .set_font_size(text_size)
def from_f0r_position(fp) : return \ Vector(fp.x, fp.y)
def dimensions(self): dims = RSVG.DimensionData() rsvg.rsvg_handle_get_dimensions(self._rsvgobj, ct.byref(dims)) return \ Vector(dims.width, dims.height)
def visualize_single(self, code_point, check_out_dir=True, x=None, y=None): """Write rendered text image for specific code point to output directory, text is positioned at (x, y). If both x and y are set to None (default), the text will be centered. Args: code_point: Str, single unicode code point. check_out_dir: Bool, set True if need to check output directory. x: Int, x coordinate of the position of text, in number of pixels. y: Int, y coordinate of the position of text, in number of pixels. Returns: file_path: Str, path to file. The filename of .png Raises: OSError: if specified directory cannot be created. """ # Get absolute directory path out_dir_abs = os.path.join(os.getcwd(), self.out_dir) if check_out_dir: self._check_create_out_dir_abs(out_dir_abs) # Create and configure ImageSurface figure_dimensions = Vector(self.image_size, self.image_size) surface = qah.ImageSurface.create(format=self._cairo_format, dimensions=figure_dimensions) # Create context ctx = qah.Context.create(surface) # Select anti-aliasing style in font options font_options = ctx.font_options font_options.antialias = self._antialias # Set color ctx.set_source_colour(self._canvas_color) # Paints background ctx.paint() ctx.set_source_colour(self._text_color) # Set font face and size ctx.set_font_face(self._font_face) ctx.set_font_size(self._font_size) ctx.set_font_options(font_options) # Position text if x is None and y is None: self._center_text(ctx, code_point) elif x is None or y is None: raise ValueError("Expect both x and y to be specified for " "alternative positioning.") else: self._position_text(ctx, code_point, x, y) # Show text, flush ImageSurface ctx.show_text(code_point) surface.flush() # Write to file filename = self._get_filename(code_point) file_path = os.path.join(out_dir_abs, filename) surface.write_to_png(file_path) return file_path
# buf.add_str(substr) # buf.guess_segment_properties() # hb.shape(hb_font, buf) # new_glyphs, end_glyph_pos = buf.get_glyphs(glyph_pos) # glyph_pos = end_glyph_pos # glyphs.extend(new_glyphs) #end for # Do the Cairo font setup, and figure out how big an `ImageSurface` we need: # In[19]: glyphs = [] glyph_pos = Vector(0, 0) buf.reset() buf.add_str(text_line) buf.guess_segment_properties() hb.shape(hb_font, buf) new_glyphs, end_glyph_pos = buf.get_glyphs(glyph_pos) glyph_pos = end_glyph_pos glyphs.extend(new_glyphs) [g.index for g in glyphs] # In[1]: glyph_array = buf.get_glyphs_codepoint() print(glyph_array)
def render(self, g, at_time, from_pos, from_extent, to_pos, to_extent) : "updates the current state of the pattern and draws it into destination qahirah.Context" \ " g. The line from Vectors from_pos to to_pos defines the starting and ending" \ " points of the animation trajectory, while from_extent and to_extent define the extents" \ " of the image perpendicular to this direction at these points, the ratio of the values" \ " defining the amount of perspective foreshortening." from_pos = Vector.from_tuple(from_pos) to_pos = Vector.from_tuple(to_pos) base_offset = self.time_to_offset(at_time) if self.last_draw_time != at_time : if self.last_draw_time == None : self.last_draw_time = - self.duration / self.steps #end if this_offset = self.time_to_offset(self.last_draw_time) time_steps = 0 while this_offset != base_offset : time_steps += 1 this_offset -= 1 if this_offset < 0 : this_offset += self.steps #end if this_time = self.last_draw_time + time_steps * self.duration / self.steps self.draw(self.get_context(this_time), this_time) #end while self.last_draw_time = at_time #end if angle = (to_pos - from_pos).angle() self.pix.flush() g.save() g.translate(from_pos) g.rotate(angle) # orient source pattern parallel to x-axis g.translate(- from_pos) span = abs(to_pos - from_pos) for i in range(0, math.ceil(span)) : dst_width = min(span - i, 1) dst_extent = i / span * (to_extent - from_extent) + from_extent dst_extent2 = (i + dst_width) / span * (to_extent - from_extent) + from_extent # conversion from coords in destination image to offsets in source image # uses reciprocals to simulate perspective foreshortening. Note offsets # are from base_offset - 1, not base_offset, because column of pixels # drawn at time t = 0 is at far right (x = steps - 1). this_offset = \ ( ( (1 / dst_extent - 1 / from_extent) / (1 / to_extent - 1 / from_extent) * self.steps + base_offset - 1 ) % self.steps ) this_offset2 = \ ( ( (1 / dst_extent2 - 1 / from_extent) / (1 / to_extent - 1 / from_extent) * self.steps + base_offset - 1 ) % self.steps ) if this_offset2 < this_offset : this_offset2 += self.steps #end if dst_x = from_pos.x + i src_rect = Rect(this_offset, 0, this_offset2 - this_offset, self.extent) dst_rect = Rect(dst_x, from_pos.y - dst_extent / 2, dst_width, dst_extent) self.pat.matrix = dst_rect.transform_to(src_rect) g.set_source(self.pat) g.new_path() g.rectangle(dst_rect) g.fill() #end for g.restore()
# ) # return glyphs # In[67]: #di.keys() # In[68]: spaceWidth = di['space'] surfx, surfy = di['surf_dim'] font_path = di['font'] font_size = di['font_size'] lines = di['lines'] fsize = Vector(int(surfx), int(surfy)) line_spacing = di['line_spacing'] # In[69]: # Creating Surface pix = qah.ImageSurface.create(format=CAIRO.FORMAT_RGB24, dimensions=fsize) # In[70]: # Creating ft_face ft_face = ft.new_face(font_path) text_size = font_size # Creating Buffer buf = hb.Buffer.create() # setting char size to font face
def render_multiline(self, font, text): """ renders multiline TEXT on the pygame surface SURF with the font style FONT. A new line in text is denoted by \n, no other characters are escaped. Other forms of white-spaces should be converted to space. returns the updated surface, words and the character bounding boxes. """ # Adding Custom Code here by removing the Orginal Code # get the number of lines lines = text.split('\n') lengths = [len(l) for l in lines] # font parameters: line_spacing = font.get_sized_height() + 1 # initialize the surface to proper size: line_bounds = font.get_rect(lines[np.argmax(lengths)]) fsize = (round(2.0 * line_bounds.width), round(1.25 * line_spacing * len(lines))) #surf = pygame.Surface(fsize, pygame.locals.SRCALPHA, 32) space = font.get_rect('O') spaceWidth = space.width * 0.85 ## 0.8 has been multiplied here surfx, surfy = fsize font_path = font.path font_size = font.size #lines = di['lines'] fsize = Vector(int(surfx + space.width), int(surfy + line_spacing)) #line_spacing = di['line_spacing'] pix = qah.ImageSurface.create(format=CAIRO.FORMAT_RGB24, dimensions=fsize) # Creating ft_face ft_face = ft.new_face(font_path) text_size = font_size # Creating Buffer buf = hb.Buffer.create() # setting char size to font face ft_face.set_char_size(size=text_size, resolution=qah.base_dpi) # ft_face.underline = font.underline hb_font = hb.Font.ft_create(ft_face) qah_face = qah.FontFace.create_for_ft_face(ft_face) ctx = qah.Context.create(pix) # ctx.set_source_colour(Colour.grey(0)) # ctx.paint() ctx.set_source_colour(Colour.grey(1)) ctx.set_font_face(qah_face) ctx.set_font_size(text_size) # Start Replacing Code from here ## for the purpose of shifting in horizontal direction. shiftAdditional = 0 # By What factor shifting should be done shiftFactor = 1.1 factor = 0 y = 0 bb = [] ## The recent addtion code. feb 19,2019 ## Project make faster. ## No need for the word wise bounding box. So, now they can be eliminated. ''' The procedure is as follow. - Since we do not require individual character bounding box, we will discard that functionality. - We will place a word and create fake bounding box for it. - right from the top left. - width of the bounding box will be simply ((width of word)/total bounding box) ''' ## Ends here feb 19,2019 for l in lines: # picking up a line. l = l.split() l = " ".join(l) x = spaceWidth * 0.7 # carriage-return y += (line_spacing * 0.8) # line-feed words = l.split() for w in words: st_bound, glyph_3 = get_Bound_Glyph(w, buf, hb_font, ft_face, text_size) shift = shiftFactor * (st_bound.topleft)[0] + shiftAdditional ## since now we have required information for rendering. ## We know bounding box, we know glyphs, time to plot. char_in_w = len(w) avg_bounding_width = st_bound.width / char_in_w ## for each character we have to place a fake bounding box width_shift = 0 for i in range(char_in_w): ## bounding box consist of top-left point + width and height. bb.append( np.array([ x + shift + width_shift, y + (st_bound.topleft)[1], avg_bounding_width, st_bound.height ])) width_shift = width_shift + avg_bounding_width ## now since we have generated fake bounding box, ## next task will be to render glyphs on the actual surface. ## Remember context is a pen for us. ## Go to the point from where you want to write. ctx.translate(Vector(x + shift, y)) # setting the color that we wish to use. ctx.set_source_colour(Colour.grey(1)) # setting the font_face ctx.set_font_face(qah_face) # defining the size. ctx.set_font_size(text_size) # rendering the glyphs on the surface. ctx.show_glyphs(glyph_3) ## translate back to the original position. ctx.translate(Vector(-(x + shift), -y)) ## Shift the x to new position. x = x + st_bound.width + shift + spaceWidth ## resetting the shift. shift = 0 # for l in lines: # l = l.split() # l = " ".join(l) # #print(spaceWidth) # x = spaceWidth*0.7 # carriage-return # y += (line_spacing*0.8) # line-feed # prev_tot_wid = 1000 # st = '' # ln = len(l) # i = 0 # bbCount = 0 # charLen = 0 # diffCount = 0 # shift = 0 # for ch in l: # render each character # if ch.isspace(): # just shift # st_bound,glyph3 = get_Bound_Glyph(st,buf,hb_font,ft_face,text_size) # shift = shiftFactor*(st_bound.topleft)[0] + shiftAdditional # bb.append(np.array([x+shift,y+(st_bound.topleft)[1],st_bound.width,st_bound.height])) # bbCount += 1 # ctx.translate(Vector(x+shift,y)) # ctx.set_source_colour(Colour.grey(1)) # ctx.set_font_face(qah_face) # ctx.set_font_size(text_size) # ctx.show_glyphs(glyph3) # # ctx.glyph_path(glyph3) # # ctx.stroke() # ctx.translate(Vector(-(x+shift),-y)) # diffCount = charLen - bbCount # for faltuItr in range(diffCount): # bb.append(np.array([x+shift,y+(st_bound.topleft)[1],st_bound.width,st_bound.height])) # bbCount = 0 # charLen = 0 # x+= st_bound.width+shift # x += spaceWidth # st = '' # prev_tot_wid = 1000 # else: # charLen += 1 # curr_bound,glyph1 = get_Bound_Glyph(ch,buf,hb_font,ft_face,text_size) # if i == 0: # factor = curr_bound.width/3.5 # upto_bound,glyph2 = get_Bound_Glyph(st+ch,buf,hb_font,ft_face,text_size) # if (upto_bound.width)+factor < prev_tot_wid+curr_bound.width: # # st = st + ch # prev_tot_wid = upto_bound.width # shift += shiftFactor*(upto_bound.topleft)[0] + shiftAdditional # else: # st_bound,glyph3 = get_Bound_Glyph(st,buf,hb_font,ft_face,text_size) # shift += shiftFactor*(st_bound.topleft)[0] + shiftAdditional # bb.append(np.array([x+shift,y+(st_bound.topleft)[1],st_bound.width,st_bound.height])) # bbCount += 1 # ctx.translate(Vector(x+shift,y)) # ctx.set_source_colour(Colour.grey(1)) # ctx.set_font_face(qah_face) # ctx.set_font_size(text_size) # ctx.show_glyphs(glyph3) # # ctx.glyph_path(glyph3) # # ctx.stroke() # ctx.translate(Vector(-(x+shift),-y)) # x+= st_bound.width+shift # st = ch # prev_tot_wid = curr_bound.width # shift = 0 # if i == ln-1: # # shift = (st_bound.topleft)[0] # st_bound,gly5 = get_Bound_Glyph(st,buf,hb_font,ft_face,text_size) # shift = shiftFactor*(st_bound.topleft)[0] + shiftAdditional # ctx.translate(Vector(x+shift,y)) # # ctx.set_source_colour(Colour.grey(0)) # # ctx.paint() # #glyphs = get_glyphs(st) # ctx.set_source_colour(Colour.grey(1)) # ctx.set_font_face(qah_face) # ctx.set_font_size(text_size) # ctx.show_glyphs(gly5) # # ctx.glyph_path(gly5) # # ctx.stroke() # ctx.translate(Vector(-(x+shift),-y)) # bb.append(np.array([x+shift,y+(st_bound.topleft)[1],st_bound.width,st_bound.height])) # bbCount += 1 # diffCount = charLen - bbCount # for fitr in range(diffCount): # bb.append(np.array([x+shift,y+(st_bound.topleft)[1],st_bound.width,st_bound.height])) # charLen = 0 # bbCount = 0 # i += 1 ########################## Replacing of the code end here ################## ############################### img = pngB_to_np(pix.to_png_bytes()) #dicc= {} #dicc['img'] = img[:,:,1] #dicc['bb'] = bb Simg = img[:, :, 1] # self.ii = self.ii+1 #bb = dicc['bb'] bb = np.array(bb) # Simg = Simg.astype(np.uint8) # Simg = Simg[:,:,1] Simg = Simg.swapaxes(0, 1) # get the union of characters for cropping: # r0 = pygame.Rect(bbs[0]) # rect_union = r0.unionall(bbs) # Simg1 = Simg1.swapaxes(0,1) # get the words: words = ' '.join(text.split()) #bbs = np.array(bbs) # f=open('temp2.pkl','rb') # bb = pickle.load(f) # bb = np.array(bb) # crop the surface to fit the text: # bbs = np.array(bbs) r0 = pygame.Rect(bb[0]) rect_union = r0.unionall(bb) surf_arr, bbs = crop_safe(Simg, rect_union, bb, pad=5) surf_arr = surf_arr.swapaxes(0, 1) #self.visualize_bb(surf_arr,bbs) return surf_arr, words, bbs
# font_path = di['font'] # font_size = di['font_size'] # lines = di['lines'] # fsize = Vector(int(surfx),int(surfy)) # line_spacing = di['line_spacing'] # spaceWidth = d['space'] # surfx,surfy = d['surf_dim'] font_path = d['font'] font_size = d['font_size'] l = d['word_text'] # lines = d['lines'] fsize = d['fsize'] line_spacing = d['line_spacing'] fsize = Vector(int(fsize[0]), int(fsize[1])) pix = qah.ImageSurface.create(format=CAIRO.FORMAT_RGB24, dimensions=fsize) # In[663]: # Creating ft_face ft_face = ft.new_face(font_path) text_size = font_size # Creating Buffer buf = hb.Buffer.create() # setting char size to font face ft_face.set_char_size(size=text_size, resolution=qah.base_dpi) hb_font = hb.Font.ft_create(ft_face) qah_face = qah.FontFace.create_for_ft_face(ft_face)
def render_curved(self, font, word_text): """ use curved baseline for rendering word """ wl = len(word_text) isword = len(word_text.split()) == 1 # do curved iff, the length of the word <= 10 if not isword or wl > 10 or np.random.rand() > self.p_curved: return self.render_multiline(font, word_text) # create the surface: lspace = font.get_sized_height() + 1 lbound = font.get_rect(word_text) fsize = (round(2.0 * lbound.width), round(3 * lspace)) font_path = font.path font_size = font.size space = font.get_rect('O') spaceWidth = space.width * 0.85 line_spacing = font.get_sized_height() + 1 fsize = Vector(int(fsize[0] + spaceWidth), int(fsize[1] + spaceWidth)) pix = qah.ImageSurface.create(format=CAIRO.FORMAT_RGB24, dimensions=fsize) # Creating ft_face ft_face = ft.new_face(font_path) text_size = font_size # Creating Buffer buf = hb.Buffer.create() # setting char size to font face ft_face.set_char_size(size=text_size, resolution=qah.base_dpi) hb_font = hb.Font.ft_create(ft_face) qah_face = qah.FontFace.create_for_ft_face(ft_face) ctx = qah.Context.create(pix) ctx.set_source_colour(Colour.grey(0)) ctx.paint() bbs = [] word_text = word_text.strip() word_text_len = len(word_text) ### Added on feb, 22, 2019 ## single word will be there. shiftFactor = 1.0 shiftAdditional = 0 ## Please refer to multiline for explaination. st_bound, glyph_3 = get_Bound_Glyph(word_text, buf, hb_font, ft_face, text_size) shift = shiftFactor * (st_bound.topleft)[0] + shiftAdditional x = spaceWidth * 0.7 + shift y = line_spacing * 0.8 st_bound, glyph_3 = get_Bound_Glyph(word_text, buf, hb_font, ft_face, text_size) ctx.translate(Vector(x + shift, y)) ctx.set_source_colour(Colour.grey(1)) ctx.set_font_face(qah_face) ctx.set_font_size(text_size) ctx.show_glyphs(glyph_3) img = pngB_to_np(pix.to_png_bytes()) curveIntensity = np.random.randint(-20, 20) img = transform_desire(img, curveIntensity) left, top, width, height = boundB(img[:, :, 1]) avg_w = width / word_text_len extd = 0 for i in range(word_text_len): bbs.append(np.array([left + extd, top, avg_w, height])) extd = extd + avg_w # # ### Code add end feb, 22, 2019 # # word_text = glyphList(l,line_spacing,buf,hb_font,ft_face,text_size) # # wl = len(word_text) # # # actual_len,wl # # # In[665]: # # mid_idx = wl//2 # # bsln = BaselineState() # # BS = bsln.get_sample() # # curve = [BS['curve'](i-mid_idx) for i in range(wl)] # # # some changes # # if wl <= 1: # # curve[mid_idx] = 0 # # else: # # curve[mid_idx] = -(np.sum(curve)/(wl-1)) # # # In[666]: # # rots = [-int(math.degrees(math.atan(BS['diff'](i-mid_idx)/(font_size/2)))) for i in range(wl)] # # # In[667]: # # # /rots # # # In[668]: # # rect = get_rect(word_text[mid_idx],qah_face,text_size,angle=0) # # # In[669]: # # leftx = pix.width/2 - rect.width/2 # # topx = pix.height/2 +rect.height/2 +curve[mid_idx] # # rect2 = (leftx,topx) # # rect.top = topx # # rect.left = leftx # # (rect.left,rect.top) # # # In[670]: # # # In[671]: # # mid_b = to_render(rect2, word_text[mid_idx],rots[mid_idx],ctx,fsize,qah_face,text_size) # # mid_bbs = np.array(mid_b) # # # In[672]: # # last_rect = rect # # # In[673]: # # bbs = [] # # ch_idx = [] # # for i in range(wl): # # if i == mid_idx: # # bbs.append(mid_bbs) # # ch_idx.append(i) # # continue # # if i < mid_idx: #left-chars # # i = mid_idx-1-i # # elif i==mid_idx+1: #right-chars begin # # last_rect = rect # # ch_idx.append(i) # # ch = word_text[i] # # newrect = get_rect(ch,qah_face,text_size,angle=0) # # newrect.top = last_rect.top # # if i > mid_idx: # # (newrect.left,newrect.top) = (last_rect.topleft[0]+last_rect.width+2, newrect.topleft[1]) # # else: # # (newrect.left,newrect.top) = (last_rect.topleft[0]-2-newrect.width, newrect.topleft[1]) # # newrect.top = max(newrect.height, min(fsize[1] - newrect.height, newrect.middle[1] + curve[i])) - newrect.height/2 # # try: # # bbrect = to_render((newrect.left,newrect.top),ch,rots[i],ctx,fsize,qah_face,text_size) # # except ValueError: # # bbrect = to_render((newrect.left,newrect.top), ch,0,ctx,fsize,qah_face,text_size) # # bbs.append(np.array(bbrect)) # # last_rect = newrect # # bbs_sequence_order = [] # # bbs_sequence_order = [None for i in ch_idx] # # for idx,i in enumerate(ch_idx): # # bbs_sequence_order[i] = bbs[idx] # # bbs = bbs_sequence_order # # diffCount = actual_len - wl # # bblast = bbs[wl-1] # # for faltuItr in range(diffCount): # # bbs.append(np.array([bblast[0],bblast[1],bblast[2],bblast[3]])) # # pix.flush().write_to_png('spcurved.png') # img = pngB_to_np(pix.to_png_bytes()) #dicc= {} #dicc['img'] = img[:,:,1] #dicc['bb'] = bbs #pl = open('save_curve.pkl','wb') # print("saved") #pickle.dump(dicc,pl,protocol=2) #pl.close() #f=open('save_curve.pkl','rb') #dicc = pickle.load(f) Simg1 = img[:, :, 0] # plt.imsave('croppedImage/spcurved'+str(self.jj)+'.png', Simg1) #self.jj = self.jj+1 bb = bbs bb = np.array(bb) Simg1 = Simg1.swapaxes(0, 1) # crop the surface to fit the text: # bbs = np.array(bbs) # surf_arr, bbs = crop_safe(pygame.surfarray.pixels_alpha(surf), rect_union, bb, pad=5) r0 = pygame.Rect(bb[0]) rect_union = r0.unionall(bb) surf_arr, bbs = crop_safe(Simg1, rect_union, bb, pad=5) surf_arr = surf_arr.swapaxes(0, 1) # plt.imsave('/home/jaya/abc.jpg',surf_arr) return surf_arr, word_text, bbs