Thursday, December 31, 2015

Python: Installing Numpy & Scipy

两个Package 64bit地址,安装方法:CMD切换至Package下载目录,
1
pip install scipy-0.17.0rc1-cp27-none-win_amd64.whl

Wednesday, December 30, 2015

Python: Compile Python Script to Binary Executable

Summary

开贴介绍Python脚本文件转化为.exe的方法。为更好的理解下面的过程,请按照示例步骤操作,准备工作需要安装PyinstallerwxPython

Example

先制作一个演示程序app.py,
1
2
3
4
5
6
#!/usr/bin/env python
import wx
app = wx.App(False)
frame = wx.Frame(None, wx.ID_ANY, "Hello World")
frame.Show(True)
app.MainLoop()
在Python Shell中执行上面这段代码,弹出Fig. 1窗口。
Fig. 1
创建.exe文件
启动Windows之CMD,将当前目录定位至app.py所在文件夹之下,键入
1
pyinstaller.exe --onefile --windowed app.py
稍等片刻,运行结束出现如Fig. 2提示,app.exe文件输出在当前目录之子目录dist。
Fig. 2
下面来解释一下上面命令中的选项:
  • --onefile指定所有相关的文件都打包至一个文件,如果不指定,输出app.exe文件周围会出现很多与之相关的文件
  • --windowed避免运行时出现控制台窗口(Console Window),若这一程序没有图形操作,这个选项可以忽略
  • app.py输出程序的主要源文件,这一文件名称将来会被用来命名.exe文件,或者,也可以另其指定名称,以--name选项命名。
这里注意不需要声明引入很多package,因为代码中已经包含这些声明。
在我的机器上,最终的app.exe文件达到8.61MB。这一文件真的是很大,因为Python解码器、程序代码和所有必需的Packages(命令指定--onefile选项)。尽管这很简单,但你要在输出之前了解这些内容。
After the build, an app.spec file will be created. This file contains all of the options used to run PyInstaller, and can be fed back into PyInstaller for future builds in place of the command line options, if desired.
添加Icon
在IconEden上为刚刚创建的app.exe文件自定义一个Icon,将此Icon置于app.py相同目录,命令稍加修改如下:
1
pyinstaller.exe --onefile --windowed --icon=app.ico app.py
稍等编译,编译完成后出现的app.exe文件如下:
Fig. 3
Matlab调用
正常

References

[3] IconEden.

Python: Installing wxPython Package

在wxPython官网下载页面,选择与安装机器匹配的安装程序,此处安装机器是Win7 64bit和Python 2.7 64bit,对应wxPython3.0-win64-3.0.2.0-py27.exe,下载完成后双击开始安装,安装完成后在Shell中键入import wx,无返回错误即表示安装成功,如Fig. 1。
Fig. 1

References

[1] http://www.wxpython.org.

Python: Install Pyinstaller Package

Summary

PyInstaller is a program that freezes (packages) Python programs into stand-alone executables, under Windows, Linux, Mac OS X, FreeBSD, Solaris and AIX. Its main advantages over similar tools are that PyInstaller works with Python 2.7 and 3.3—3.5, it builds smaller executables thanks to transparent compression, it is fully multi-platform, and use the OS support to load the dynamic libraries, thus ensuring full compatibility.
The main goal of PyInstaller is to be compatible with 3rd-party packages out-of-the-box. This means that, with PyInstaller, all the required tricks to make external packages work are already integrated within PyInstaller itself so that there is no user intervention required. You'll never be required to look for tricks in wikis and apply custom modification to your files or your setup scripts. As an example, libraries like PyQt, Django or matplotlib are fully supported, without having to handle plugins or external data files manually. Check our compatibility list of Supported Packages for details.

Installing

之前已经安装pip,此时需要下载pyinstaller安装包(下载地址见参考文献[2]),Windows之CMD环境中先将当前目录设定在安装文件夹之下,输入pip install pyinstaller,安装完成返回结果如Fig. 1,安装成功。
Fig. 1

References

Thursday, December 17, 2015

Tool: Applications

[1] Lockhunter, unlocking files and folders!
[3] CorelDraw表格文字统一修改:编辑>>全选>>文本, 就可以全部选中文字了,然后改字体和大小.
[4] CorelDRAW图形嵌入文字的调整,主要是图上两处.
[8] 析出水平/垂直线段:选择“表格”工具,在画纸上拉出一个表格;Ctrl+Q将表格转换为曲线;Ctrl+U取消组合对象,此时表格各线段独立.
[9] 任务栏程序图标丢失的解决方法,Solution Answered by Mark Berry.
1
2
3
4
DEAZV-27TFM-BL52D-PVN9L-ADULD <2021-6-11到期>
DEAZW-38TGM-HH52D-XG5WR-FX4QW <2021-6-11到期>
DMAZW-48TGM-LQ52C-G82V6-2JJUC <2021-6-10到期>
DMAZW-4ATGM-QL52D-M6XEM-TCFCS <2021-6-11到期>
[11] CorelDraw插入摄氏度符号(插入字符):
[14] 修改Win7系统字体.
[15] 插入Arial字体%.
[16] 笔记本计算机,若FX键不正常,可以使用组合键Fn+FX.
[18] MathType空心字母,对应文本状态.
[24] Vivaldi Browser, Visual Tabs.

Wednesday, December 16, 2015

Matlab: NetCDF File

What is NetCDF?

NetCDF (Network Common Data Form) is a set of software libraries and self-describing, machine-independent data formats that support the creation, access, and sharing of array-oriented scientific data. The project homepage is hosted by the Unidata program at the University Corporation for Atmospheric Research (UCAR). They are also the chief source of netCDF software, standards development, updates, etc. The format is an open standard. NetCDF Classic and 64-bit Offset Format are an international standard of the Open Geospatial Consortium.
以sst.mon.ltm.1981-2010.nc(details)文件为例,SST(Sea Surface Temperature)在ArcGIS10.2中显示如图 1。
图 1

Matlab操作

以sst.mon.ltm.1981-2010.nc文件为例,Matlab操作读入及输出为GeoTiff文件。
Spatial Coverage:
1.0 degree latitude x 1.0 degree longitude global grid (360x180).
89.5N - 89.5S, 0.5E - 359.5E.
Missing grids are 9.999e+20(ltm).
代码运行生产Jan.~Dec.全球SST,程序运行流畅。

See Also

Monday, December 14, 2015

ArcGIS: Generate Raster Longitude and Latitude

Summary

栅格数据怎样可以得到逐点的经纬度信息,并分别将经度、纬度坐标以二维矩阵形式(影像)输出?
已知mask.tif文件已投影为WGS_1984_UTM_zone_50N,行列分别是411、452,空间分辨率1000m。

Steps

- Convert a raster of the study area to point.
打开ArcToolBox,Conversion--From Raster--Raster to Point,处理结果返回points.shp。
- Create two fields (floating or double) to store x and y.
右键points,Open Attribute Table,在属性表中添加2个域,分别列出经度、纬度,如Fig. 1。
Fig. 1
- Calculate geometry (longitude for x, latitude for y)
在属性名称上右键选择Calculate Geometry ...,经度对应x,纬度对应y,注意单位选择Decimal Degrees,如Fig. 2,计算结果将会存储在属性表中。
Fig. 2
- Convert to raster using x field (longitude raster)
打开ArcToolBox,Conversion--To Raster--Point to Raster,参数配置如Fig.3,像元参数设置与mask.tif一致。
Fig. 3
输出纬度矩阵与mask.tif空间信息完全一致,如Fig. 4。
Fig. 4

References

[2] Specifying the precision and scale allows you to restrict the range of values and number formats a field can accept, giving you greater control. For example, if you specify a float with a precision of 4 and a scale of 2, the field will accept 12.34. If you try to enter 12.345 into the field, an error message would display, as this exceeds the maximum number of digits and decimal places allowed. On the other hand, if you specify a float with a precision of 5 and a scale of 3, the field would let you enter 12.345.

Matlab: Conversion from GeoTiff Format to Arc/Info Grid

Summary

我在之前的帖子已经讨论过Arc/Info Grid或IDRISI Grid转换为GeoTiff格式文件的方法。此处,本帖讨论Geotiff文件转换为Arc/Info Grid文件的代码。
这里的方法只考虑到了像元经向、纬向空间分辨率一致的情况,对于这二者不一致的情况还没有做讨论,留待以后再考虑。
这一方法可以适用于任意投影的Geotiff文件。

Sunday, December 13, 2015

Matlab: Booting Error

Summary

个别情况下,Matlab会在启动时出现警告错误:
Error using connector.internal.autostart.run
Cannot CD to C:\Users\UserName\AppData\Local\Temp (Name is nonexistent or not a directory).
这个错误的原因是Temp文件的权限被操作系统默认加固,解决方法有二,启动Matlab时以管理员身份运行,或者增加Temp的访问权限。如果放任这一警告,运行一般程序也是可以的,但是不能启动Parallel处理。

References

Matlab: Parallel Process

Summary

并行处理对于耗时很长很长的程序至关重要,它的思路是空间换时间,将一条处理流在空间允许前提下提升至多条。
此处,介绍并行处理功能将以函数parfor为主要切入点,它比较容易理解和掌握。Matlab中涉及并行处理的函数还有很多,以后在逐渐补充之。

parfor

函数parfor与for语句定义几乎一致,不同在于:循环起止数值必须是有限整数,或者这一区间是可以用表达式代表的一个连续整数的行向量。M定义最大数量的Matlab Workers(什么是worker?),他们运行parfor循环中语句,M只能是非负整数。默认情况下,Matlab利用尽可能多的workers。如果被设定上限,Matlab利用的workers不会超过这个数量,即是存在更多的空间。如果请求数量大于实际情况,Matlab只能在声明之处使用最大数量可利用的workers。注意循环体内各循环必须是独立的,比如按顺序第900次与其他各次过程均不存在联系,放在400次之前运行依然得到相同的结果,这就是各次独立原则。
我在这里举例说明一些情况:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
clear;
clc;

n=100;

disp('parfor');
timebegin=tic;
cur_data=date;
cur_time=fix(clock);
str1=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time Begin: ');
fprintf(str1);
fprintf('\n');

dirpath='./sub1';
parfor ii=1:n
    txtname=[num2str(ii), '.txt'];
    txtpath=[dirpath, '/', txtname];
    fid=fopen(txtpath, 'wt');
    fclose(fid);
    fclose('all');
    disp(num2str(ii));
end

cur_data=date;
cur_time=fix(clock);
str2=sprintf('%s %.2d:%.2d:%.2d', cur_data, cur_time(4), cur_time(5), cur_time(6)); 
fprintf('Time End: ');
disp(str2);
timespan=toc(timebegin);
fprintf('Time Span: %.4f s\n', timespan);
上面代码创建100个txt文件,并输出每次创建文件的序号,如Fig. 1,它的顺序不是按照1至100排列的,但不损害结果的正确。
Fig. 1

Transparency

若运行parfor返回错误:See Parallel Computing Toolbox documentation about Transparency,这表示parfor代码Body违反了透明性原则(Transparency)。
透明性原则的定义是The body of a parfor-loop or spmd block must be transparent, meaning that all references to variables must be "visible" (i.e., occur in the text of the program).函数parfor循环主体必须是完全透明的,这指的是所有与变量相关的内容必须是可见的。
这种透明性原则下诸如函数save、load、eval等都是不能出现在parfor代码主体中的,若仍要实现以上函数的功能,其实也很简单,把这些函数包装成子函数(subfunction)调用即可,此时代码主体不违反透明性原则。

Cannot Be Classified

对于此类错误the variable XX in a parfor cannot be classified.,原因是XX在循环之前已被赋值,导致循环体之内不能再被赋值,这种情况可以考虑如下解决方式
1
2
3
4
5
XX=[];
parfor ii=1:n
    value=??
    XX=AddData(XX, value);
end

References

Saturday, December 12, 2015

Tool: FlowChart

Summary

A flowchart is a type of diagram that represents an algorithm, workflow or process, showing the steps as boxes of various kinds, and their order by connecting them with arrows. This diagrammatic representation illustrates a solution model to a given problem. Flowcharts are used in analyzing, designing, documenting or managing a process or program in various fields.
Fig. 1

References

Saturday, December 5, 2015

Matlab: Gaussian Model

Summary

开贴记录数据拟合之高斯函数。
已知一组数据,x表示数值,y表示频率,如Fig. 1所示,图形非常接近高斯分布。
Fig. 1

Method

(1)拟合高斯模型,手动方法
在Command Window,键入cftool,出现Curve Fitting Tool。如Fig. 2所示,配置xy及Gaussian。
Fig. 2
配置完成后,软件自动得到返回参数,R-square达0.9814,非常高,右侧图形也显示拟合高斯曲线与原始情况较为吻合。(试试改变图中Number of terms?)
此时得到的高斯函数:
\[f\left( x \right) = 1946 \cdot {e^{ - {{\left( {\frac{{x - 442.9}}{{82.13}}} \right)}^2}}}\]
(2)代码方法
见Codefit.m,与手动方法返回结果一致。如Fig.3所示,Fitted Curve是为高斯曲线。Over。
Fig. 3

Further Discussion

尽管该数据通过高斯拟合方法可以使得被解释的方差高达98%,但是该高斯函数的二阶导数等于0的解仍不能得到实数,更准确的说通过拟合逼近这一曲线仍不能得到该曲线的拐点。参考Blocking A Non-Stationary Signal Using Wavelets,将这一曲线视为非平稳信号,经连续小波变化(Mexican hat)处理,直接得到这一信号的二阶导数,找到二阶导数为0的序列。
Fig. 4
Fig. 4从左至右的2图表示1~200尺度下的二阶导数,显然在Scale大于75之后,黑线仅与两条0等值线相交,3、4图表示Scale=100/150的情况,对应拐点是469和383。

References

Friday, December 4, 2015

Matlab: Embedding Images

Summary

代码操作一张图片嵌入另一图片之特定位置。

Code Specification

对于需要嵌入的图片,首先操作它缩放一定比例,scale定义缩放比例。在原始图片Fig. 1嵌入另一图片,得到Fig. 2,。
Fig. 1
Fig. 2
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
% Created by LI Xu
% Version 1.0
% 12 April, 2015

% Improved by LI Xu
% Version 1.1
% December 4, 2015
% Set the input/output directories
% for processing

clear;
clc;
clf;

% Front Picture
frontpath='legend.png';
front=imread(frontpath);
% Scale Factor
scale=0.18;
front=imresize(front, scale);
frontrow=size(front, 1);
frontcol=size(front, 2);
% Source Directory
SouDir='./input';
% Destination Directory
DesDir='./output';

% Set the start location of row and column
hratio=0.57;
vratio=0.8;

% Background Picture
files=dir([SouDir, '/*.png']);
for ii=1:length(files)
    
    filename=files(ii).name;
    filepath=[SouDir, '/', filename];
    back=imread(filepath);
    row=size(back, 1);
    col=size(back, 2);
    
    strow=round(row*vratio);
    stcol=round(col*hratio);
    
    
    resimg=back;
    resimg(strow:strow+frontrow-1, stcol:stcol+frontcol-1, :)=front;
    
    imshow(resimg);
    pause(2);
    
    otpath=[DesDir, '/', filename];
    % Save
    imwrite(resimg, otpath);
    close all;
    disp([num2str(ii), '.', filename]);
    
end

disp('***********************************************');

Tuesday, December 1, 2015

Matlab: Recognizing the Valid Range

Summary

代码识别影像有效数值区间,并显示有效数值之数量。

Code Specification

配置igValues忽略数值,输出有效数值数量及范围如Fig. 1。
Fig. 1
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
% Created by LI Xu
% Version 1.0
% December 2, 2015

% Description:
% Recognize the valid range for the input image

% If you have any question about this code,
% please do not hesitate to contact me via E-mail: 
% jeremy456@163.com

% Blog:
% http://blog.sciencenet.cn/u/lixujeremy
% http://lixuworld.blogspot.com/

clear;
clc;

% Values for Ingnoring
igValues=[-99, 100];
% Source Directory
SouDir='./input';
% All files
files=dir([SouDir, '/*.tif']);
% Loop
for ii=1:length(files)
    filename=files(ii).name;
    filepath=[SouDir, '/', filename];
    image=imread(filepath);
    data=image;
    imgsz=size(data);
    num=imgsz(1)*imgsz(2);
    data=reshape(data, 1, num);
    for jj=1:length(igValues)
        igV=igValues(jj);
        index=find(data==igV);
        if isempty(index)
            continue;
        end
        data(index)=[];       
    end
    
    % Max
    max_data=max(data);
    % Min
    min_data=min(data);
    % Display
    fprintf('%d-%s-%d: ', ii, filename, length(data));
    fprintf('%.5f~%.5f\n', min_data, max_data);
    
end

disp('*********************************************');

Monday, November 30, 2015

Standardized Precipitation-Evapotranspiration Index

The SPEI fulfils the requirements of a drought index since its multi-scalar character enables it to be used by different scientific disciplines to detect, monitor and analyze droughts. Like the sc-PDSI and the SPI, the SPEI can measure drought severity according to its intensity and duration, and can identify the onset and end of drought episodes. The SPEI allows comparison of drought severity through time and space, since it can be calculated over a wide range of climates, as can the SPI. Moreover, Keyantash and Dracup (2002) indicated that drought indices must be statistically robust and easily calculated, and have a clear and comprehensible calculation procedure. All these requirements are met by the SPEI. However, a crucial advantage of the SPEI over other widely used drought indices that consider the effect of PET on drought severity is that its multi-scalar characteristics enable identification of different drought types and impacts in the context of global warming.
SPEI详细的介绍请见Vicente-Serrano SM, et al., 2010。随论文,Vicente-Serrano开发了SPEI Calculator程序,其中PET应用仅包含温度参数的计算方法(Thornthwaite, 1948),这个程序自由下载,使用说明参考spei_manual_en.pdf。
应对SPEI批量操作需求,我在不掌握SPEI计算过程的基础上,以Matlab调用SPEI Calculator程序实现批量SPEI指数计算,具体情况见附件中SPEI_Cal.m和SPEI_Batch.m,代码运行流畅,调用返回结果正确。
图 1~3分别表示1-、3-、6-、9-、12-month尺度SPEI指数,Orig-12-month SPEI是测试数据附带的测试结果。
图 1
图 2
图 3
如图 3所示,上下两图干湿交替情况基本相同。不过,仔细查看两组数据,我们发现数据之间仍存在微小的差异,比如1901年1月12-month的SPEI在上下两图分别为1.152和1.164104,原因可能在于SPEI Calculator运行环境的差异,但不表示本地运行的前者是错误结果。
SPEI干旱/湿润等级划分(Yu, et al., 2014)

CategoriesSPEI values

Extremely drynessLess than - 2
Severe dryness-1.99 to -1.5
Moderate dryness-1.49 to -1.0
Near normal-1.0 to 1.0
Moderate wetness1.0 to 1.49
Severe wetness1.50 to 1.99
Extremely wetnessMore than -2

附上测试代码及数据(SPEI.rar)。
附上栅格处理参考代码(SPEIcal.rar)。

References

[1] SPEI.
[3] Vicente-SerranoSM, Beguería S, López-Moreno JI (2010) A multiscalar drought index sensitive to global warming: the standardized precipitation evapotranspiration index. Journal of Climate, 23, 1696-1718.
[4] Thornthwaite CW (1948) An approach toward a rational classification of climate. Geographical Review, 55-94.
[6] Yu M, Li Q, Hayes MJ, Svoboda MD, Heim RR (2014) Are droughts becoming more frequent or severe in China based on the standardized precipitation evapotranspiration index: 1951–2010? International Journal of Climatology, 34, 545-558.

Matlab: Rendering Automatically

Summary

全自动二维图像渲染程序,将单波段图像按照唯一数值(Unique Value)和区间数值(Classified Value)进行RGB渲染。

Settings

文件Info.xlsx记录渲染配置的颜色,分别是唯一数值(Fig. 1)和区间数值(Fig. 2),第一列标示代码的含义(中英文皆可,服务于理解),不做运算处理,之后的2~3或2~4列参与运算。在区间数值运算中,区间遵循(第二列,第三列】规则对应第四列RGB。
Fig. 1
Fig. 2
Fig. 3是代码运行结果,Fig. 4是手动渲染结果,两者别无二致。
Fig. 3
Fig. 4
注意:当代码渲染结果放入ArcGIS中,它会被自动拉伸,这并不是我们想要的情况,只要在属性(Properties)中设置Stretch Type: None,并取消勾选Apply Gamma Stretch,见Fig. 5。
Fig. 5

Wednesday, November 25, 2015

Matlab: Quadratic Fit

周期性变量的趋势不能用线性回归进行拟合,周期性波动不符合线性特征,可以考虑应用一元二次曲线拟合,例如月降水量在一年内的变化。
图 1是某地多年1~12月平均降水量的变化情况,一年12个月正好是月降水量的完整变化周期,尝试一元二次曲线拟合这个周期性的变化趋势,以R2表示方差解释率,p-value表示回归模型的显著性。
Fig. 1
图 2显示R2为0.5602,表示约有56%的方差可以被解释,比例还比较高。p-value为0.0248,若以α=0.05为显著水平,则p-value<α,通过显著性检验,该模型成立。
Fig. 2
栅格运算(单波段多波段).

Tuesday, November 24, 2015

Matlab: 不同Size图片镶嵌

开贴介绍不同Size图片的镶嵌方法,不同Size的图片是指图片的行列不相同的多个图片。
以两个不同Size的图片为例,运用代码实现图片在右侧或下方自动调整后的镶嵌操作,1.jpg有817行815列,2.jpg有799行800列。我们的目标是实现图 1的两种效果。镶嵌过程中1.jpg的Size不变,但2.jpg依情况有对应的调整。
图 1
函数imresize()操作2.jpg,依据镶嵌的行或列调整2.jpg。以水平镶嵌(keyword控制)为例,根据1.jpg有817行而得调整之后的2.jpg的伸缩Scale是1.0225,伸缩后Size是817×819。代码处理结果如图 2和3,毫无违和。
图 2
图 3
MatMerge_2.rar.上下左右批量镶嵌.2018-03-02.

Tool: 网易邮箱插入图像签名的方法

  1. 上传图片至网易相册(或者其他更容易获取的地方,如公开的博客),获取该图片地址。
  2. 打开网易邮箱,点写信,在写信正文栏插入该图片。
  3. 点击选取图片,调整至中意的签名用大小尺寸,然后复制该图片。
  4. 点右上角“设置”,然后选“签名设置”;在签名设置页面下点“添加签名”。
  5. 在添加签名的正文部分点右键粘贴图片,即能把该图片放入签名档。
  6. 加入签名档名称及签名的其他内容,保存即可。

Matlab: Enhanced Mosaic Operation

Summary

若干图片还是要求具有同样的尺寸,并含有相同的波段数量。

Code Specification

代码前端设定这些内容:
  1. N=2;定义输出列数
  2. color=[255, 255, 255];定义输出背景颜色
  3. blkimg.width=0.04;定义插入图片之间水平方向间距,归一化为图片的width
  4. blkimg.height=0.04;定义插入图片之间垂直方向间距,归一化为图片的height
  5. edgimg.width=0;定义图片与边缘之间水平方向间距,归一化为图片的width
  6. edgimg.height=0;定义图片与边缘之间垂直方向间距,归一化为图片的height
如果blkimg.width、blkimg.height、edgimg.width、edgimg.height四变量全部赋值为0,此时结果将与下面代码结果一致,不留出任何空白,见Fig. 1。
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
% Created by LI Xu
% Version 1.0
% 25 October, 2014

% Modified by LI Xu
% Version 1.1
% November 24, 2015
% Add Source and destination directory

% Mosaicing Images with the same
% rows, columns and banks.
% No blank edges.

clear;
clc;

% Set the number of columns for Output M*N
N=2;

% Source Directory
SouDir='./input';
% Destination Directory
DesDir='./output';

% Images
files=dir([SouDir, '/*.png']);
num_files=length(files);
M=ceil(num_files/N);

% Image Info
img=imread([SouDir, '/', files(1).name]);
rows=size(img, 1);
cols=size(img, 2);
bands=size(img, 3);

cellstack=cell(M, 1);
N_flag=1;
temp_img=zeros(rows, cols*N, bands)+255;
temp_img=uint8(temp_img);
for ii=1:num_files
    imgfile=files(ii).name;
    in_img=imread([SouDir, '/', imgfile]);
    
    % Position
    if N_flag > N
        N_flag=1;
        temp_img=zeros(rows, cols*N, bands)+255;
        temp_img=uint8(temp_img);
    end
    cellrow=ceil(ii./N);
    row_position=1:rows;
    col_position=1+cols*(N_flag-1):cols*N_flag;
    temp_img(row_position, col_position, :)=in_img;
    %imshow(temp_img);
    cellstack{cellrow, 1}=temp_img;
    
    N_flag=N_flag+1;
end


% Output Image
otImage=zeros(rows*M, cols*N, bands);
for row=1:M
    row_range=1+rows*(row-1):rows*row;
    otImage(row_range, :, :)=cellstack{row, 1};
end

otImage=uint8(otImage);
imshow(otImage);
pause(2);

otname=['NoEdge_R', num2str(M), 'C', num2str(N), '.png'];
otpath=[DesDir, '/', otname];
imwrite(otImage, otpath);
close all
disp('END');

Fig. 1
其他时候可以是这样的:
Fig. 2
Fig. 3
MatMosaic1.2.rar.灰度与彩色图片混搭.

References

Monday, November 23, 2015

Matlab: Insert Text

Summary

Matlab如何在图片上更灵活地插入文字是一个不断发展的主题,立足于自身需求及对代码的理解,这一问题今天有一新的回答。当然,目前Matlab在图片中插入文字仅仅支持ASCII编码,也就是不支持中文字符。

Code Specification

代码重点在设置待插入文字的属性。举例:
  1. stratts_1.fontname='Arial';
  2. stratts_1.fontsize=0.08; 文字大小,归一化为图片height的比例
  3. stratts_1.fontcolor=[255, 215, 0]; 文字颜色
  4. stratts_1.xscale=0.05; X轴起始位置,归一化为图片width的比例
  5. stratts_1.yscale=0.05; Y轴起始位置,归一化为图片height的比例
  6. stratts_1.rowinterval=0.2; 多行文字的行间距,归一化为图片height的比例
  7. stratts_1.Opacity=1; 文字透明度
此处,代码从.xslx文件中录入待插入文字,属性fontsize、xscale、yscale、rowinterval若大于1则认为是绝对数值,增加代码的可移植性。以下Fig.1~4是一些插入文字的结果:
Fig. 1
Fig. 2
Fig. 3
Fig. 4
这个小程序还有不足之处,未来继续改进。

References