+-
我是个新手,公司派了个关于IOS图片分析的任务给我,我尝试过网络上大部分的代码,而现在我的代码是这个样子:
extension UIImage {
func isRed() -> Bool {
let type = self.cgImage?.bitmapInfo.pixelFormat
let width = Int(self.size.width)
let height = Int(self.size.height)
let imageData = self.cgImage!.dataProvider!.data
let data: UnsafePointer = CFDataGetBytePtr(imageData)
let scale = UIScreen.main.scale
// for ind in 0..<200000 {
// Logger.debug("liu-526 <-" + CGFloat(data[ind]).description + "->")
// }
var redPixel = 0
Logger.debug("liu-526 " + self.cgImage!.bitsPerPixel.description)
for pixelX in 0..<width {
for pixelY in 0..<height {
let address: Int = ((Int(self.size.width) * Int(CGFloat(pixelY) * scale)) + Int(CGFloat(pixelX) * scale)) * 4
let position1 = CGFloat(data[address])
let position2 = CGFloat(data[address + 1])
let position3 = CGFloat(data[address + 2])
let position4 = CGFloat(data[address + 3])
let position5 = CGFloat(data[address + 4])
// Logger.debug("liu-526 <-" + position1.description + "," + position2.description + "," + position3.description + "," + position4.description + "->")
var red = 0
var green = 0
var blue = 0
switch type {
case .rgba:
red = Int(position1)
green = Int(position2)
blue = Int(position3)
case .bgra:
red = Int(position3)
green = Int(position2)
blue = Int(position1)
case .abgr:
red = Int(position4)
green = Int(position3)
blue = Int(position2)
case .argb:
red = Int(position2)
green = Int(position3)
blue = Int(position4)
default:
break
}
let postr1 = " x:" + pixelX.description + " y:" + pixelY.description + " "
let postr = postr1 + " adr:" + address.description + " "
Logger.debug("liu-525 " + postr + position1.description + "-" + position2.description + "-" + position3.description + "-" + position4.description + "-" + position5.description)
if red > (((green + blue) / 2) + 10) {
redPixel += 1
}
// Logger.debug("liu-13r " + r.description)
// Logger.debug("liu-13g " + g.description)
// Logger.debug("liu-13b " + b.description)
}
}
return redPixel > (width * height) / 2
}
}
我认为判断类型是不必要的,但无论判断和不判断我都无法获取正确的图片:
输入的图片:
输出的图片: