python numpy matplotlib畫小方塊填充背景色和新增不同色彩的文字
阿新 • • 發佈:2018-12-29
需要根據不同的數值生成不同色彩的小方塊,並標明數值,考慮到各種色彩的方塊,如果採用文字採用黑色或者白色總是避免不了和背景色重複,所以把數值轉化成rgb(0x11,0xf0,0x3b)類似的值,然後文字採用rgb(255-0x11,255-0xf0,255-0x3b),要把背景色的rgb轉成十進位制再進行減法操作,這裡為了方便陳述,用的十六進位制沒有轉。
這裡的filename為需要做方塊圖的數值,按一定格式存在此檔案中例如:
11&330&a346&5789&
44&c3&20&11
按自己數值存放的格式解析就好了,總之得到需要作圖的數值,按一定的方式轉成rgb後再作圖,或者自己挑選幾種、幾十種類似這樣的#0012ce色彩值對應自己的數值也行,
import numpy as np import matplotlib matplotlib.use('Agg') import matplotlib.pyplot as plt import os import cv2 import re #按固定長度擷取字串 img_output_path='/home/xxx/image/' class draw_sequences(): def __init__(self, idx): #背景顏色為黑色的畫布 #im = np.zeros((300, 300, 3), dtype="uint8") #3 #背景顏色為白色的畫布` self.im = np.ones((800,600,3),np.uint8)*255 #畫布使用預設字型 self.font = cv2.FONT_HERSHEY_SIMPLEX #起始作圖座標 self.leftx = 10 self.lefty = 10 #矩形單元長高 self.len = 70 self.high = 15 self.filepath = img_output_path + '/' + idx #第idx張畫布(也許一張不夠) self.idx = idx self.bdraw = False self.filename = filename #畫一個矩形序列單元 def draw_sequence(self, listseq): if self.leftx + self.len > 600: self.leftx = 10 self.move_down() self.bdraw = True #矩形邊框顏色 #cv2.rectangle(self.im, (self.leftx, self.lefty), (self.leftx+self.len, self.lefty+self.high), (int(listseq[0],16),int(listseq[1],16),int(listseq[2],16))) #12 #填充矩形顏色 rseq = int(listseq[0],16) gseq = (int(listseq[1],16)+100)%255 bseq = (int(listseq[2],16)+50)%255 cv2.rectangle(self.im, (self.leftx, self.lefty), (self.leftx+self.len, self.lefty+self.high), (rseq, gseq, bseq), thickness=-1) #填充文字 seq = "&".join(str(i) for i in listseq) cv2.putText(self.im,seq,(self.leftx, self.lefty+10), self.font, 0.4, (255-rseq, 255-gseq,255-bseq), 1) self.move_right() #儲存序列圖 def write_jpg(self): if self.bdraw == True: cv2.imwrite(self.filepath + ".jpg", self.im) self.idx = self.idx + 1 self.__init__(self.idx) #往右移一個位置畫序列單元 def move_down(self): self.lefty = self.lefty + self.high self.leftx = 10 if self.lefty >= 800: self.write_jpg() #另起一行畫序列單元 def move_right(self): self.leftx = self.leftx+self.len cdraw = draw_sequences("", filemd5, 0) txtread = open(filename,"r") for line in txtread: sub_seqs = i.split('&') sub_seqs.pop() idx = 0 lseq = [] for i in sub_seqs: if len(i) > 2: subseqs = re.findall(r'.{2}', i) for j in subseqs: lseq.append(j) if (idx+1)%3 == 0: cdraw.draw_sequence(lseq) lseq = [] idx = idx+1 else: lseq.append(i) if (idx+1)%3 == 0: cdraw.draw_sequence(lseq) lseq = [] idx = idx+1 listlen = len(lseq) if (listlen): if listlen < 3: for i in range(listlen,3): lseq.append('00') cdraw.draw_sequence(lseq) cdraw.move_right() cdraw.write_jpg() del cdraw
這裡是一行數值作一張圖,&符號分割後的數字兩位兩位劃分,不夠的用0補,每6位數字作一個方塊