def find_independent_zeros(C): zeroArray = np.zeros((C.shape[0], C.shape[1])) for i in range(C.shape[0]): num = 0 for j in range(C.shape[1]): if C[i, j] == 0: num = 1 zeroArray[i, j] = num M = [] # 已经找到了独立0元素的行 for j in range(5): '找到最少0值所在的行' countZero = np.count_nonzero(zeroArray == 1, axis=1) # 统计每一行的零元素的个数 for i in range(len(countZero)): if countZero[i] == 0 or i in M: countZero[i] = 10000 temp = np.argmin(countZero) # 确定最少零元素个数的行索引 M.append(temp) column = np.where(zeroArray[temp, :] == 1)[0] # 一行中0元素的所有列索引 p = 0 for i in column: '第一个0不改变' if p == 0: p += 1 else: zeroArray[temp, i] = -1 for k in range(C.shape[0]): if zeroArray[k, column[0]] == 1 and k not in M: zeroArray[k, column[0]] -= 2 return zeroArray 优化代码
时间: 2024-04-17 11:28:48 浏览: 55
2.1图像目标边界描述.zip_4 3 2 1_ZEROS-7_图像目标边界描述
def find_independent_zeros(C):
zeroArray = np.zeros((C.shape[0], C.shape[1]))
countZero = np.count_nonzero(C == 0, axis=1) # 统计每一行的零元素的个数
sorted_rows = np.argsort(countZero) # 按照零元素个数排序的行索引
M = [] # 已经找到了独立0元素的行
for row in sorted_rows:
if countZero[row] == 0 or row in M:
continue
column = np.where(C[row, :] == 0)[0] # 当前行的所有零元素的列索引
zeroArray[row, column[1:]] = -1
for k in range(C.shape[0]):
if zeroArray[k, column[0]] == 1 and k not in M:
zeroArray[k, column[0]] -= 2
M.append(row)
return zeroArray
# 优化后的代码会按照行中零元素个数的升序来处理,减少了不必要的计算和循环次数。如果有其他方面的要求或者问题,请告诉我。
阅读全文