Implementation using python drawing in excel

I. Introduction

Before college, to learn how much N to see God use EXCEL excel drawing, I feel very weird. Today, school for a month python, expanded wanted to use excel drawing. Of course, in fact, use the word drawing less strict, in fact, is the use of opencv through each pixel rgb value, and then convert it to hexadecimal, the last call openpyxl can be filled.

1.1, achieve results

Results as shown file

1.2, the installation need to use the library

We need to use the library as follows:

import cv2 #导入OpenCV库
import xlsxwriter #利用这个调整行高列宽
import openpyxl #利用这个填充颜色
import numpy as np #下面这两个是数据存储的两种方式,用此种方式处理数据,比列表高效,具体可自行查看文档
import pandas as pd

In addition to the first library the other can be installed directly at the command prompt pip, or use the editor of a number of automatic installation function is also very convenient, specific see section III of this article.

The first library if you install directly with pip3 install opencv-python, then, no matter how fast your speed will slow very few k / s, as follows:

file

If installed okay, wait a few minutes and some may be the key does not work, the word red line to see dozens of headache occurs directly. Baidu several times after that is the source of installation problems, switch to domestic sources to install, use the following command: install -i PIP3 https://pypi.tuna.tsinghua.edu.cn/simple OpenCV-Python

Below, I am ready to install speed and taken for comparison to the above, the results directly installed

file

Second, the code explain separately

In this paper we use object-oriented programming were thinking.

2.1, the object definition and initialization

class ImageToExcel():
def __init__(self,image_path,excel_path):
self.imgviewx=cv2.imread(image_path,cv2.IMREAD_COLOR)
self.excel_path=excel_path

The first two lines is well understood format and initialize the object definition object.

Image_path and excel_path which of these two variables is your image and subsequent storage path excel file save location.

The third line self.imgviewx = cv2.imread (image_path, cv2.IMREAD_COLOR) means that the call of imread opencv read picture. Wherein the first parameter is instantiated when the object is passed in the image storage path. This function returns a three-dimensional array, respectively, x, y, rgb is x, y coordinates corresponding rgb values, where x, y units of one pixel. Finally, the three-dimensional array to a property of the object imgviewx, wait for a subsequent object method calls. We will print it out as follows.

file

Fourth row attribute << self.excel_path = excel_path >> is an object instantiation when the passed excel_path passed to objects excel_path, the same method calls wait for a subsequent object.

2.2, object methods

1: row height adjustment column width, to prevent image deformation

#excel行高列宽调整
def excel_size(self):
workbook = xlsxwriter.Workbook(self.excel_path)
worksheet = workbook.add_worksheet('test')
worksheet.set_column('A:CAA', 1)
for x in range(2000):worksheet.set_row(x, 8.4)
workbook.close()

In fact, you can follow this adjustment can also excel in.

Second row and third row basic one to understand is that in the beginning you instantiate an object when passed a path to create a workbook and add a worksheet named test.

A third line means that the column to the column width for column 1 is provided CAA (Note: there is one set do not know why the worksheet is 0.94, the same dot column width)

The fourth line means the same, but not high-volume line only through the cycle.

Like last looked like close, in fact, the most important function is saved without this line, in front of all the settings will not be saved.

2.3, the method of the object into hexadecimal binary 2:10

#10进制转化为16进制
def ten2_16(self,num):
num1 = hex(num).replace('0x', '')
return num1 if len(num1) > 1 else '0' + num1

This method is not elaborate, is a function of the use of the system comes into hex 10 hex 16 hex. We all know that the beginning of the hex is 0x hex returned, and the hex color code is not clear, so they need to replace removed.

If the rgb values ​​are less than 16 to 16 words will be displayed in hexadecimal digit, but this did not in the same hex color code, so the last line, which means that a number of words at the beginning of 0s.

2.4, the method of the object 3: acquiring r, g, b values ​​using the method 1 and converted to hexadecimal color code

#获取像素数据并转化为16进制
def get_rgb_data(self):
self.excel_size()
data_r=pd.DataFrame( np.array(self.imgviewx)[:,:,2] ).applymap(self.ten2_16)
data_g=pd.DataFrame( np.array(self.imgviewx)[:,:,1] ).applymap(self.ten2_16)
data_b=pd.DataFrame( np.array(self.imgviewx)[:,:,0] ).applymap(self.ten2_16)
return (data_r+data_g+data_b).values

Wherein the second row self.excel_size () is invoked at this call when the first method of the present method a row height adjusting column width. Behind us say, it relates to a method parameter passing between objects, we follow says.

The same code structure three hundred forty-five line, we pick a say. For example the third row data_r = pd.DataFrame (np.array (self.imgviewx) [:,:, 2]) .applymap (self.ten2_16) This code we can open into the following code:

r=np.array(self.imgviewx)[:,:,2]
tmp=pd.DataFrame( r )
data_r=tmp.applymap(self.ten2_16)

This time it is easy to understand. The first line means that the three-dimensional list rgb values ​​of all pixels included in the target object is initialized when the picture started to get into an array of r and extract them.

The second row is a first row of the array into DataFrame obtained and stored in the object variable tmp, for processing the third row.

The third line is the r values ​​were converted to hexadecimal DataFrame use of applymap.

The last line return (data_r + data_g + data_b) .values ​​means after converting into hexadecimal rgb values ​​combined to give a color code hexadecimal 16 and converted into an array.

2.5, the method of the object 4: Color Fill

def color_fill(self):
rgb_list=self.get_rgb_data()
wb = openpyxl.load_workbook(self.excel_path)
ws = wb['test']
for x,tmp1 in list(enumerate(rgb_list)):
print('总共有%s行,已填充%s行,还剩下%s行'%(len(rgb_list),x+1,len(rgb_list)-x-1))
for y ,tmp2 in list(enumerate(tmp1)):
ws.cell(x+1,y+1).fill = openpyxl.styles.fills.GradientFill(stop=[str(tmp2),str(tmp2)])
wb.save(self.excel_path)

The second row rgb_list = self.get_rgb_data () is not familiar, right, is called method 1 Method 2 when used.

In the present method, this is a method that is called 3 Method 2. The only difference is that there is no return value.

We call this method and the method in method 3 2 1 call. So that when outside objects we use only the object instance and call the method 3 to realize the function.

The third line, the fourth line is to call openpyxl.load_workbook open our new method in the workbook test worksheet.

Five to seven rows of two nested loops it is easy to understand is the use of loops through each worksheet.

Eighth line of code could be simplified, this is what I modify a gradient fill online code.

The last line is to save the worksheet, nothing to say.

Third, the complete code

import cv2 #导入OpenCV库
import xlsxwriter #利用这个调整行高列宽
import openpyxl #利用这个填充颜色
import numpy as np #下面这两个是数据存储的两种方式,用此种方式处理数据,比列表高效
import pandas as pd

class ImageToExcel():
#初始化
def __init__(self,image_path,excel_path):
self.imgviewx=cv2.imread(image_path,cv2.IMREAD_COLOR)
self.excel_path=excel_path
# excel行高列宽调整
def excel_size(self):
workbook = xlsxwriter.Workbook(self.excel_path)
worksheet = workbook.add_worksheet('test')
worksheet.set_column('A:CAA', 1)
for x in range(2000): worksheet.set_row(x, 8.4)
workbook.close()
#rgb转16进制颜色码
def ten2_16(self,num):
tmp = hex(num).replace('0x', '')
return tmp if len(tmp) > 1 else '0' + tmp
#获取像素数据并转化为16进制
def get_rgb_data(self):
self.excel_size()
data_r=pd.DataFrame( np.array(self.imgviewx)[:,:,2] ).applymap(self.ten2_16)
data_g=pd.DataFrame( np.array(self.imgviewx)[:,:,1] ).applymap(self.ten2_16)
data_b=pd.DataFrame( np.array(self.imgviewx)[:,:,0] ).applymap(self.ten2_16)
return (data_r+data_g+data_b).values
#颜色填充
def color_fill(self):
rgb_list=self.get_rgb_data()
wb = openpyxl.load_workbook(self.excel_path)
ws = wb['test']
for x,tmp1 in list(enumerate(rgb_list)):
print('总共有%s行,已填充%s行,还剩下%s行'%(len(rgb_list),x+1,len(rgb_list)-x-1))
for y ,tmp2 in list(enumerate(tmp1)):
ws.cell(x+1,y+1).fill = openpyxl.styles.fills.GradientFill(stop=[str(tmp2),str(tmp2)])
wb.save(self.excel_path)
excel_path='test23.xlsx'
image_path='tttt.png'
image=ImageToExcel(image_path,excel_path)
image.color_fill()
最后四行前两行可以直接写在第三行中,就是对象的实例化中
另外还有一点,image_path中的 tttt.jpg是直接和我的py文件放在一起的,不然运行会报错。

IV Conclusion

Well, all this stuff is all done, of course, there are many to note:

First, the red, green and blue extraction number 3 in this section is contrary to extract when needed attention.

as follows:

file

Of course, you can also try changing this value to see what would be the final result. Blue sun, red sky or a green hat, this played a yourselves.

Second, in addition to more thing to note, there is a need to note is that pixels can not be too high. I tested under 342 * 218, then my i7-6700u open excel not very fluent.

You can traverse the time to two pixels or four pixels in steps, but I have not tried this, it may be more obvious grainy (own guess not tried), or modifications to the original picture.

Published 38 original articles · won praise 1 · views 2185

Guess you like

Origin blog.csdn.net/wulishinian/article/details/104944050