[英]Find numbers of seperated chunks in 2d file from file Python
Sorry in advance if the title was a bit confusing, not sure how to word it better 抱歉,标题有点混乱,不确定如何写得更好
In python, if you were to have a seperate 'file.txt' containing the following text: 在python中,如果要单独包含包含以下文本的“ file.txt”:
.....%%%%%..% %%%...%%...%% %.....%%%..%% ...%%.....%%% ....%%.....%% .....%%%..%%% %%%%....%%%..
Representing splatters of paint, I'm trying to find a way to output the number of individual chunks, in this case this would return '4', I'm having trouble visualising how I would go about doing this, any help would greatly be appreciated. .....%%%%%..% %%%...%%...%% %.....%%%..%% ...%%.....%%% ....%%.....%% .....%%%..%%% %%%%....%%%..
代表油漆,我正在尝试为了找到一种方法来输出单个块的数量,在这种情况下,它将返回“ 4”,我在可视化如何执行此操作时遇到了麻烦,将不胜感激。 Thanks! 谢谢!
I'm still not sure what is a "chunk" but this assumes that it's a cluster of %
elements: 我仍然不确定什么是“块”,但这假设它是%
元素的簇:
import numpy as np
from scipy import ndimage
pattern = [];
with open('patterns.txt', 'r') as f:
for line in f:
line = line.replace('%','1').replace('.','0').replace('',' ')
pattern.append((line.strip(' \n ')).split())
image = np.array(pattern, dtype = int)
pstruct = [[1,1,1],[1,1,1],[1,1,1]]
labeled_array, num_features = ndimage.measurements.label(image,structure = pstruct)
This program reads your input file of .
该程序读取的输入文件.
and %
into a nested list. 和%
放入嵌套列表中。 It turns all %
to 1 and .
它将所有%
变为1和.
to 0 and generates a numpy
array of integers with 1 and 0 representing your original pattern. 设为0,并生成一个numpy
整数数组,其中1和0代表原始模式。 It then uses a scipy
function to look for clusters of 1s. 然后,它使用scipy
函数查找1的簇。
pstruct
defines what is considered a cluster, and when the default is used it produces 5 chunks, for details look here https://docs.scipy.org/doc/scipy-.14.0/reference/generated/scipy.ndimage.measurements.label.html . pstruct
定义了什么是集群,使用默认集群时会生成5个块,有关详细信息,请参见https://docs.scipy.org/doc/scipy-.14.0/reference/generation/scipy.ndimage.measurements。 label.html 。
labeled_array
are chunks numbered by their cluster number and num_features
is the number of clusters. labeled_array
是按簇号编号的块, num_features
是簇数。
If this does not properly define your chunk, clarify it a bit more or even better - upload an image where you explicitly mark the chunks. 如果这不能正确定义您的块,请对其进行更多甚至更好的说明-在您明确标记块的位置上传图片。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.