我有一个513*513的矩阵,它表示人分割的结果。
现在我想把不规则的连接区域转换成矩形。
它看起来像下面的图像:
的数据
我的代码是:
func findConnectedRegion(matrix: [[Int]]) -> [[(Int, Int)]] {
var result: [[(Int, Int)]] = []
// var visited: Set<(Int, Int)> = []
var visited: Set<String> = []
let numRows = matrix.count
let numCols = matrix[0].count
for i in 0..< numRows {
for j in 0..< numCols {
let position = (i, j)
self.str = String(i)+"-"+String(j)
if matrix[i][j] == 15 && !visited.contains(self.str) {
var region: [(Int, Int)] = []
dfs(matrix: matrix, rows: numRows,cols: numCols,position: position, visited: &visited, region: ®ion)
result.append(region)
}
}
}
return result
}
func dfs(matrix: [[Int]],rows:Int,cols:Int,position: (Int, Int), visited: inout Set<String>, region: inout [(Int, Int)]) {
// let numRows = matrix.count
// let numCols = matrix[0].count
let numRows = rows
let numCols = cols
let (row, col) = position
self.str = String(position.0)+"-"+String(position.1)
// Check if the current position is within bounds and is part of the region
guard row >= 0, row < numRows, col >= 0, col < numCols, matrix[row][col] == 15, !visited.contains(self.str) else {
return
}
visited.insert(self.str)
region.append(position)
// Explore neighbors in all four directions
dfs(matrix: matrix,rows: numRows,cols: numCols, position: (row - 1, col), visited: &visited, region: ®ion) // Up
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row + 1, col), visited: &visited, region: ®ion) // Down
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col - 1), visited: &visited, region: ®ion) // Left
dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col + 1), visited: &visited, region: ®ion) // Right
}
字符串
但它总是有一个错误,如线程1:EXC_BAD_ACCESS(code=2,address=0xxxxxxx)
它看起来像一个堆栈溢出错误,但我不确定。我怎么才能解决这个问题?
arrayFile在这里:https://gofile.io/d/Ijmok8
将其转换为数组:
if let data = try? Data(contentsOf: filePath, options: .mappedIfSafe),
let array = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves) {
}
型
我想做的是把不规则的15个相连的区域变成矩形。
然后通过以下方式绘制图像:
func drawImage(array: [[Int]], completion: @escaping (UIImage?) -> Void) {
let m = array.count
let n = array[0].count
let size = CGSize(width: m, height: n)
DispatchQueue.global(qos: .userInitiated).async {
let renderer = UIGraphicsImageRenderer(size: size)
let image = renderer.image { (context) in
let cgContext = context.cgContext
let black = UIColor.black
let white = UIColor.white
for j in 0..<n {
for i in 0..<m {
let value = array[i][j]
let rect = CGRect(x: i, y: j, width: 1, height: 1)
if value == 15 {
cgContext.setFillColor(black.cgColor)
cgContext.fill(rect)
} else {
cgContext.setFillColor(white.cgColor)
cgContext.fill(rect)
}
}
}
}
DispatchQueue.main.async {
completion(image)
}
}
型
结果与右上角的图像不一样,如果它显示矩形也没关系。
谢谢
1条答案
按热度按时间tyg4sfes1#
很可能,是的,你遇到了一个内存错误,由于
String
的巨大Set
.我对你的代码做了一些修改,使用了
Set<CGPoint>
,不再出现崩溃(还添加了一点代码来在形状周围绘制矩形):字符串
测试结果:
x1c 0d1x的数据
我使用了你的json文件.不知道如果你有一个更大的数组,这是否会再次遇到问题-我将把它留给你测试。
顺便说一下,您可能希望使用Vision框架研究
VNDetectContoursRequest
。