如何在iOS中将2D矩阵中的不规则连接区域转换为矩形?

How to convert irregular connected regions in a 2D matrix into rectangles in iOS?

提问人:magic_9527 提问时间:11/15/2023 最后编辑:magic_9527 更新时间:11/16/2023 访问量:37

问:

我有一个 513*513 矩阵,表示人员分割的结果。

现在我想将不规则的连接区域转换为矩形。

如下图所示:

1

我的代码是:

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: &region)
                    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: &region)  // Up
        dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row + 1, col), visited: &visited, region: &region)  // Down
        dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col - 1), visited: &visited, region: &region)  // Left
        dfs(matrix: matrix, rows: numRows,cols: numCols,position: (row, col + 1), visited: &visited, region: &region)  // Right
    }

但它总是有一个错误,如线程 1:EXC_BAD_ACCESS(代码=2,地址=0xxxxxxx) 2

这看起来像堆栈溢出错误,但我不确定。我该如何解决这个问题?

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)
            }
            
            
        }

结果与右上角的图像不同,如果它显示矩形也没关系。

谢谢

IOS 矩阵 深度 广度优先搜索

评论

0赞 DonMag 11/15/2023
很难猜到你在做什么 - 对你的代码进行快速、简单的测试不会抛出错误。如果您发布足够的代码来重现错误,我们也许可以提供帮助。
0赞 magic_9527 11/16/2023
@DonMag 对不起,我的错。我有附加演示文件和代码。我想做的是将 15 个不规则连接的区域变成矩形。

答:

0赞 DonMag 11/16/2023 #1

很可能,是的,由于巨大的...SetString

我对您的代码进行了一些编辑,以代替使用并且不再崩溃(还添加了一些代码以在形状周围绘制矩形):Set<CGPoint>

// we want to use a Set of CGPoint
//  so we need to make it Hashable
extension CGPoint : Hashable {
    public func hash(into hasher: inout Hasher) {
        hasher.combine(x)
        hasher.combine(y)
    }
}

class MatrixVC: UIViewController {
    
    let imgView = UIImageView()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = .systemYellow
        
        imgView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(imgView)
        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([
            imgView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            imgView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            imgView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
        ])
        
        guard let filePath = Bundle.main.url(forResource: "arrayFile", withExtension: "json") else { fatalError() }
        
        if let data = try? Data(contentsOf: filePath, options: .mappedIfSafe),
           let array = try? JSONSerialization.jsonObject(with: data, options: .mutableLeaves),
           let a = array as? [[Int]]
        {
            let t = findConnectedRegion(matrix: a)
            
            var rects: [CGRect] = []
            
            for i in 0..<t.count {
                let mnx = t[i].min(by: { $0.0 < $1.0 }) ?? (0, 0)
                let mxx = t[i].max(by: { $0.0 < $1.0 }) ?? (0, 0)
                let mny = t[i].min(by: { $0.1 < $1.1 }) ?? (0, 0)
                let mxy = t[i].max(by: { $0.1 < $1.1 }) ?? (0, 0)
                
                let r: CGRect = .init(x: mnx.0, y: mny.1, width: mxx.0 - mnx.0, height: mxy.1 - mny.1)
                rects.append(r)
            }
            
            drawImage(array: a, rects: rects, completion: { img in
                guard let img = img else { fatalError() }
                self.imgView.heightAnchor.constraint(equalTo: self.imgView.widthAnchor, multiplier: img.size.height / img.size.width).isActive = true
                self.imgView.image = img
            })

        }
    }
    
    func drawImage(array: [[Int]], rects: [CGRect], 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 rectColors: [UIColor] = [
                .systemRed, .systemGreen, .systemBlue
            ]
            
            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)
                        }
                        
                    }
                }
                
                for i in 0..<rects.count {
                    cgContext.setStrokeColor(rectColors[i % rectColors.count].cgColor)
                    cgContext.stroke(rects[i])
                }
                
            }
            
            DispatchQueue.main.async {
                completion(image)
            }
            
            
        }
    }
    
    var curPoint: CGPoint = .zero
    
    func findConnectedRegion(matrix: [[Int]]) -> [[(Int, Int)]] {
        var result: [[(Int, Int)]] = []
        var visitedPoints: Set<CGPoint> = []
        let numRows = matrix.count
        let numCols = matrix[0].count
        
        for i in 0..<numRows {
            for j in 0..<numCols {
                let position = (i, j)
                self.curPoint = .init(x: i, y: j)
                if matrix[i][j] == 15 && !visitedPoints.contains(self.curPoint) {
                    var region: [(Int, Int)] = []
                    dfsP(matrix: matrix, rows: numRows,cols: numCols,position: position, visited: &visitedPoints, region: &region)
                    result.append(region)
                }
            }
        }
        return result
    }
    
    func dfsP(matrix: [[Int]],rows:Int,cols:Int,position: (Int, Int), visited: inout Set<CGPoint>, region: inout [(Int, Int)]) {
        let numRows = rows
        let numCols = cols
        
        let (row, col) = position
        self.curPoint = .init(x: position.0, y: 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.curPoint) else {
            return
        }
        
        visited.insert(self.curPoint)
        region.append(position)
        
        // Explore neighbors in all four directions
        dfsP(matrix: matrix,rows: numRows,cols: numCols, position: (row - 1, col), visited: &visited, region: &region)  // Up
        dfsP(matrix: matrix, rows: numRows,cols: numCols,position: (row + 1, col), visited: &visited, region: &region)  // Down
        dfsP(matrix: matrix, rows: numRows,cols: numCols,position: (row, col - 1), visited: &visited, region: &region)  // Left
        dfsP(matrix: matrix, rows: numRows,cols: numCols,position: (row, col + 1), visited: &visited, region: &region)  // Right
    }
    
}

结果:

enter image description here

我用了你的json文件...不知道如果你有一个更大的数组,这是否会再次遇到问题 - 我会把它留给你来测试。

顺便说一句,您可能需要研究 Vision 框架。VNDetectContoursRequest

评论

0赞 magic_9527 11/17/2023
谢谢你的回复!当禁用 Address SanitizerZombie Objects 时,它有效但是,当启用 Address SanitizerZombie Objects 时,为什么 Set of String 或 CGPoint 会带来内存问题?
0赞 DonMag 11/18/2023
@magic_9527 -- 我必须真正深入研究 Profiling,但只是猜测我会说它使用的内存/资源比Set<String>Set<CGPoint>