Files
photochk/Sources/Photochk/Core/DHash.swift
T
yfoxjpandClaude Opus 5 c7f68b6cca Photochk 1.0.0 — 類似写真を探して整理する macOS アプリ
フォルダ内の写真から、中身が同じものと見た目が似ているものを検出して
グループにまとめ、残す1枚を選んでほかをゴミ箱へ送れるようにする。

検出は安い判定から順に4段:
- ファイルサイズが同じものだけ SHA-256 でバイト一致を確定
- dHash(知覚ハッシュ)のハミング距離で候補ペアを抽出
- 候補に出てくる画像だけ Vision の feature print で精査
- Union-Find で連結成分をグループ化

判定のしきい値は実写画像で距離を実測して決めた(docs/calibration.md)。
tools/release-update.sh で Gitea のリリースを更新する。

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-07-28 08:02:14 +09:00

128 lines
5.0 KiB
Swift

import CoreGraphics
import Foundation
import ImageIO
/// 画像を1回デコードして得られる基本情報。dHash と表示用メタデータをまとめて取る。
struct ImageBasics: Codable, Hashable, Sendable {
let dHash: UInt64
let pixelWidth: Int
let pixelHeight: Int
let captureDate: Date?
}
/// 隣接ピクセルの明暗差から 64bit の知覚ハッシュ(dHash)を作る。
///
/// リサイズや再圧縮では値がほとんど変わらないので、feature print にかける候補ペアを
/// 安く絞り込むための一次フィルタとして使う。
enum DHash {
/// 9×8 に落として横隣接を比較するので 8×8 = 64bit になる。
private static let hashWidth = 9
private static let hashHeight = 8
static func compute(for url: URL) -> ImageBasics? {
guard let source = CGImageSourceCreateWithURL(url as CFURL, nil),
CGImageSourceGetCount(source) > 0
else { return nil }
let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any]
let (width, height) = pixelSize(from: properties)
let captureDate = captureDate(from: properties)
// フルデコードを避けるため、まず小さなサムネイルを取り出す。
// WithTransform で EXIF の回転を適用しておく。Vision の feature print も同じく EXIF を
// 反映するので、これで「表示したときの見た目」どうしを比較する形に揃う。
// 結果として、回転が焼き込まれた版と EXIF で回している版は同じ写真として検出できる一方、
// 実際に向きが違う写真どうしは別物として扱われる。
let thumbnailOptions: [CFString: Any] = [
kCGImageSourceCreateThumbnailFromImageAlways: true,
kCGImageSourceCreateThumbnailWithTransform: true,
kCGImageSourceShouldCacheImmediately: true,
kCGImageSourceThumbnailMaxPixelSize: 64,
]
guard let thumbnail = CGImageSourceCreateThumbnailAtIndex(
source, 0, thumbnailOptions as CFDictionary
) else { return nil }
guard let hash = hash(of: thumbnail) else { return nil }
return ImageBasics(
dHash: hash,
pixelWidth: width,
pixelHeight: height,
captureDate: captureDate
)
}
/// 2つのハッシュがどれだけ違うか(異なるビット数)。
static func hammingDistance(_ a: UInt64, _ b: UInt64) -> Int {
(a ^ b).nonzeroBitCount
}
// MARK: - 内部
private static func hash(of image: CGImage) -> UInt64? {
let bytesPerRow = 16 // hashWidth(9) 以上で 16 バイト境界に揃える
var buffer = [UInt8](repeating: 0, count: bytesPerRow * hashHeight)
let ok = buffer.withUnsafeMutableBytes { raw -> Bool in
guard let context = CGContext(
data: raw.baseAddress,
width: hashWidth,
height: hashHeight,
bitsPerComponent: 8,
bytesPerRow: bytesPerRow,
space: CGColorSpaceCreateDeviceGray(),
bitmapInfo: CGImageAlphaInfo.none.rawValue
) else { return false }
context.interpolationQuality = .medium
context.draw(
image,
in: CGRect(x: 0, y: 0, width: hashWidth, height: hashHeight)
)
return true
}
guard ok else { return nil }
var hash: UInt64 = 0
var bit = 0
for y in 0..<hashHeight {
let row = y * bytesPerRow
for x in 0..<(hashWidth - 1) {
if buffer[row + x] > buffer[row + x + 1] {
hash |= (1 << UInt64(bit))
}
bit += 1
}
}
return hash
}
private static func pixelSize(from properties: [CFString: Any]?) -> (Int, Int) {
let width = properties?[kCGImagePropertyPixelWidth] as? Int ?? 0
let height = properties?[kCGImagePropertyPixelHeight] as? Int ?? 0
// EXIF の回転を反映した「見た目の」サイズを返す。
let orientation = properties?[kCGImagePropertyOrientation] as? Int ?? 1
return (5...8).contains(orientation) ? (height, width) : (width, height)
}
private static func captureDate(from properties: [CFString: Any]?) -> Date? {
guard let exif = properties?[kCGImagePropertyExifDictionary] as? [CFString: Any] else {
return nil
}
let raw = exif[kCGImagePropertyExifDateTimeOriginal] as? String
?? exif[kCGImagePropertyExifDateTimeDigitized] as? String
guard let raw else { return nil }
return exifDateFormatter.date(from: raw)
}
/// EXIF の日時は "2024:05:01 12:34:56" 形式。
private static let exifDateFormatter: DateFormatter = {
let f = DateFormatter()
f.locale = Locale(identifier: "en_US_POSIX")
f.dateFormat = "yyyy:MM:dd HH:mm:ss"
return f
}()
}