import Jimp from './jimp' ; const url = require ( 'url-loader!./assets/cephalo.jpg' ) ; let _ref = null ; async function readReferenceImage ( ) { if ( ! _ref ) { _ref = await Jimp . read ( url ) ; console . info ( 'Reference image loaded' ) ; } return _ref ; } const getAspectRatio = ( img ) => img . bitmap . width / img . bitmap . height ; const getDistance = ( img , ref ) => Jimp . distance ( img , ref ) ; const getPixelDiff = ( img , ref ) => Jimp . diff ( img , ref ) . percent ; const err = new Error ( 'This image does not look like a cephalometric radiograph' ) ; function isAspectRatioSatisfied ( img ) { const ratio = getAspectRatio ( img ) ; console . info ( 'Aspect ratio: %f' , ratio ) ; return ratio >= 0.70 && ratio < 1.5 ? Promise . resolve ( ) : Promise . reject ( err ) ; } async function isDistanceSatisifed ( img ) { const distance = getDistance ( img , await readReferenceImage ( ) ) ; console . info ( 'Hamming distance: %f' , distance ) ; return distance < 0.25 ? Promise . resolve ( ) : Promise . reject ( err ) ; } async function isDiffSatisfied ( img ) { const diff = getPixelDiff ( img , await readReferenceImage ( ) ) ; console . info ( 'Pixel difference %f' , diff ) ; return diff < 0.15 ? Promise . resolve ( ) : Promise . reject ( err ) ; } export async function doesLookLikeCephalometricRadiograph ( img , tryFlipX = true ) { return Promise . all ( [ isAspectRatioSatisfied ( img ) , isDistanceSatisifed ( img ) , ] ) . then ( ( ) => ( { isCephalo : true , shouldFlipX : false } ) ) . catch ( async ( ) => { if ( tryFlipX ) { const { isCephalo } = await doesLookLikeCephalometricRadiograph ( img . clone ( ) . flip ( true , false ) , false ) ; return { isCephalo , shouldFlipX : isCephalo , } ; } return { isCephalo : false , shouldFlipX : false , } ; } ) ; }