将图像拆分为 Swift 中的网格

Splitting an image into a grid in Swift

我试图通过将图像分成 100x100 的网格来将图像分成 10'000 个较小的图像。当我 运行 代码时,我收到一个 Error_Bad_Instruction.

import Cocoa
import CoreImage

public class Image {
public var image: CGImage?

     public func divide() -> [CGImage] {
        var tiles: [CGImage] = []
        for x in 0...100 {
            for y in 0...100 {

                let tile = image?.cropping(to: CGRect(x: (image?.width)!/x, y: (image?.height)!/y, width: (image?.width)! / 100, height: (image?.height)! / 100 ))
                tiles.append(tile!)

            }
        }
        return tiles
    }

    public init(image: CGImage) {
        self.image = image
    }
}

var img = Image(image: (NSImage(named: "aus-regions.jpg")?.cgImage(forProposedRect: nil, context: nil, hints: nil))!)
var a = img.divide()

您发布的代码存在一些问题:

  1. 强制环绕图像
  2. 循环包括 100 - 你只需要 99。或者如评论所建议的那样:for x in 0..<100
  3. 你在第一步中除以 0
  4. 您的算法未形成网格。

我已经更新以获得网格,使用我计算机上的图像,宽度和高度仅为 10,因为使用 100 太长了。

import Cocoa
import CoreImage

let times = 10
public class Image {
    public var image: CGImage?

    public func divide() -> [CGImage] {
        var tiles: [CGImage] = []
        for x in 0..<times {
            for y in 0..<times {

                let tile = image?.cropping(to: CGRect(x: x * (image?.width)!/times, y: y * (image?.height)!/times, width: (image?.width)! / times, height: (image?.height)! / times ))
                tiles.append(tile!)

            }
        }
        return tiles
     }

     public init(image: CGImage) {
         self.image = image
     }
 }

 if let image = NSImage(named: "bg.jpg")?.cgImage(forProposedRect: nil,   context: nil, hints: nil) {
      var img = Image(image: image)
      var a = img.divide()
 }