IOS8 Core image in Swift: Automatically improves the use of images and built-in filters
IOS8 Core Image in Swift: more complex filters
IOS8 Core Image in Swift: Face Detection and mosaics
IOS8 Core Image in Swift: Video Live Filter
The Core image is a very powerful framework. It allows you to simply apply a variety of filters to the image, such as modifying the brightness, color, or exposure. It leverages the GPU (or CPU) to process image data and video frames very quickly, even in real time. And it hides all the details of the underlying graphics processing, and it's easy to use with the API provided, without having to worry about how OpenGL or OpenGL ES can take full advantage of the GPU's capabilities, and don't need you to know how GCD works in it, and the Core image handles all the details.
The Core image Framework gives us these things:
- Built-in picture filters
- Feature detection capabilities (such as face recognition)
- Supports automatic image improvement
- Ability to combine multiple filters into a single custom filter
Automatic Image Improvement
Let's start with a simple example. Build a project with single View application's engineering template, which is built with only one appdelegate and one viewcontroller, and another Main.storyboard, in Main.storyboard has prepared a viewcontroller, we put a uiimageview in this viewcontroller, adjust its frame:
In addition, since Uiimageview is the default stretch picture, we don't want it to deform and set its contentmode to Aspect Fit. Turn the auto layout and size classes off by the way.
Finally, drag two buttons to come in, one for displaying the original image, one for automatically improving the images, and the whole viewcontroller looks like this:
Next, add the corresponding Ibaction method and the Iboutlet property in Viewcontroller:
Class Viewcontroller:uiviewcontroller {
@IBOutlet var imageview:uiimageview!
Lazy var originalimage:uiimage = {
Return UIImage (named: "Image")
}()
......
A imageview that is connected to storyboard, and a originalimage property that is lazy to load once, this property will be used many times later, here is the image I used for the whole project.
And then in the viewdidload like this:
Override Func Viewdidload () {
Super.viewdidload ()
Self.imageView.layer.shadowOpacity = 0.8
Self.imageView.layer.shadowColor = Uicolor.blackcolor (). Cgcolor
Self.imageView.layer.shadowOffset = Cgsize (width:1, height:1)
Self.imageView.image = Originalimage
}
Only two things have been done: one is to give ImageView a shadow border, just to look good, and the other is to assign Originalimage to ImageView.
A line of code shows the original:
@IBAction func showoriginalimage () {
Self.imageView.image = Originalimage
}
Here is the automatic improvement of the code, I first post it, and then slowly say, there is an intuitive effect will be more interested in some:
@IBAction func autoadjust () {
var inputimage = ciimage (image:originalimage)
Let filters = Inputimage.autoadjustmentfilters () as [Cifilter]
For Filter:cifilter in filters {
Filter.setvalue (Inputimage, Forkey:kciinputimagekey)
Inputimage = Filter.outputimage
}
Self.imageView.image = UIImage (ciimage:inputimage)
}
After connecting the ibaction and Iboutlet, you should be able to see the following effects:
Click on the automatic improvement can see the effect, may run a bit slow, because we have not done optimization, if the improvement effect is not obvious, you can click a few times the original image to compare.
Although there are some problems, it has not prevented us from continuing our exploration. The above automatic improvement code explicitly uses two classes (why should I use the word explicit here?). ): Ciimage and Cifilter, where:
- Ciimage: This is a model object that holds the data that can be used to build the image, which can be either a file or a Cifilter output object.
- cifilter: Filters, different Cifilter instances can represent different filter effects, different filters can set the same parameters, but it requires at least one input parameter and can generate an output object.
In addition, the auto-improve function of core image can intelligently view the histogram of the image (histogram? ), face area, and metadata for analysis, just pass in an image as an input parameter, and you can get a set of filters that will improve the image.
Ciimage instances can come through uiimage, and then through two api:autoadjustmentfilters and autoadjustmentfilterswithoptions: To get an array of filters that can improve the image, In most cases, you might use the API that provides the option dictionary, because you can set:
- The direction of the picture, which is especially important for filters such as Ciredeyecorrection, Cifacebalance, and so on, because the core image needs to be accurately detected across the opposite part.
- Whether you want to remove the red eye only (set Kciimageautoadjustenhance to False).
- Whether to use all filters except red eye removal (set Kciimageautoadjustredeye to False).
If you want to provide an option dictionary, you can use this:[Plain]View Plaincopyprint?
- Nsdictionary *options = @{cidetectorimageorientation:
- [[Image Properties] valueforkey:kcgimagepropertyorientation]};
- Nsarray *adjustments = [MyImage autoadjustmentfilterswithoptions:options];
In this case, I will not pass the option dictionary because there is no problem with the direction of the picture. Want to know what filters are used for automatic improvement? Just print the Filter object, which, in general, will be the 5 filters:
- ciredeyecorrection: Fix various red eye caused by camera flash
- cifacebalance: Adjust skin tone
- civibrance: Improves image saturation without affecting skin tone
- Citonecurve: Improving the contrast of images
- cihighlightshadowadjust: Improving Shadow Detail
In most cases, these filters will suffice. As mentioned before, different cifilter will have different parameters, if we want to know what parameters cifilter specific, you can call its ownInputkeysmethod, get a list of input parameters it supports, or call itsOutputkeysmethod to get a list of its output parameters (usually we just use outpuntimage), or call it directlyattributesmethod to get all of its information, including its name, its classification, input parameters, output parameters, the range of values for each parameter, and the default values. Call Cifilter's Inputkeys method to see its input parameters:
For Filter:cifilter in filters {
Let Inputkeys = Filter.inputkeys ()
Print (Filter.name ())
println (Inputkeys)
...
Printing results:
[Plain]View Plaincopyprint?
- Cifacebalance[inputimage, Inputorigi, Inputorigq, Inputstrength, inputwarmth]
- Civibrance[inputimage, Inputamount]
- Citonecurve[inputimage, InputPoint0, InputPoint1, InputPoint2, InputPoint3, InputPoint4]
- Cihighlightshadowadjust[inputimage, Inputradius, Inputshadowamount, Inputhighlightamount]
Almost all of the filters have inputimage This input parameter, we can directly use the System preset key to set parameters (such as Kciinputimagekey), the system has preset most of the common key, if you find that some key system is not preset , you can use the string that gets the key name directly as a key, such as:
Filter.setvalue (Inputimage, Forkey:kciinputimagekey)
Both are set up exactly the same way
Filter.setvalue (Inputimage, Forkey: "Inputimage")
For the automatic improvement of the image function, we do not need to know too much detail, set inputimage on it.
Next pits.
There are two problems with the above code: one is to feel noticeably slower each time the automatic improvement is used, and the other is that the image is deformed after automatic improvement. Original and improved image comparison:
I set the contentmode of the Uiimageview to Aspect Fit, which is not to want the image to deform, but to scale proportionally, if the Uiimageview background color is set to red, When the original image is displayed, you can see red on both top and bottom, and the picture after improvement is not red. Since Apple says UIImage is fully supported for Ciimage, the document does not indicate the cause of this problem, I refer to the following post:
Http://stackoverflow.com/questions/15878060/setting-uiimageview-content-mode-after-applying-a-cifilter
It says that the uiimage obtained by the UIImage (Ciimage:) method is not a standard uiimage based on cgimage, so it cannot be understood according to the general rules of display, so we need to get a real uiimage in a different way. The solution is put down below.
Before introducing Ciimage and Cifilter, we used the word explicit, because in the code you can visually see the use of these two classes, ciimage provide information about the image, Cifilter provide filters, When we call Cifilter's Outputimage method, the core image does not render the image, but computes various parameters and stores the result in the Ciimage object, only to be rendered by the third object when it is actually going to be displayed. This object is cicontext.
Cicontext is the key to core image processing images, and unlike the core graphics Cgcontext, Cicontext can be reused without having to create a new one each time, and at the same time having to output ciimage. In short, theCore image renders objects produced by Cifilter through Cicontext .
In the above example we did not use Cicontext, but when we called UIImage (ciimage:), the core image implicitly used the Cicontext internally, that is, the work we need to do manually is done automatically. But there is a problem, and it will recreate a Cicontext object every time it is called UIImage (ciimage:), which will not have a big impact if it is destroyed, but it will affect performance in the process of repeatedly using filters, in order to prevent this situation, We reuse the Cicontext object and let Viewcontroller hold a lazy-loaded property:
Lazy var context:cicontext = {
Return Cicontext (Options:nil)
}()
Cicontext requires a dictionary at initialization time, you can create a CPU-based Cicontext object by Kcicontextusesoftwarerenderer, by default creating a GPU-based Cicontext object, The difference is that the GPU's Cicontext objects are processed faster, while CPU-based Cicontext objects can be processed in the background in addition to supporting larger images. We'll pass nil. Create a GPU-based Cicontext object.
With reusable Cicontext objects, this is required when creating uiimage:
@IBAction func autoadjust () {
var inputimage = ciimage (image:originalimage)
Let filters = Inputimage.autoadjustmentfilters () as [Cifilter]
For Filter:cifilter in filters {
Filter.setvalue (Inputimage, Forkey:kciinputimagekey)
Inputimage = Filter.outputimage
}
Self.imageView.image = UIImage (ciimage:inputimage)
Let Cgimage = Context.createcgimage (Inputimage, FromRect:inputImage.extent ())
Self.imageView.image = UIImage (cgimage:cgimage)
}
While the first implementation of the automatic improvement is a bit slow (because you want to create a Cicontext object), the performance has improved a lot in the case of repeated executions, and this solves the second problem, the Contentmode problem. If there is no special case, you should always create a cgimage in this way, and then turn Cgimage into UIImage.
Use a variety of built-in filters to pass the Cifilter class methodfilternamesincategory ()You can get all the filters that belong to a category:
Func Showfiltersinconsole () {
Let Filternames = Cifilter.filternamesincategory (kcicategorybuiltin)
println (Filternames.count)
println (Filternames)
For FilterName in Filternames {
Let filter = Cifilter (Name:filtername as String)
Let attributes = Filter.attributes ()
println (attributes)
}
}
The class parameter passed in this method isKcicategorybuiltin, which means that all the filters for iOS8 Core image are output: There are 127 kinds. Of course, not all filters are used, and we canKcicategorycoloreffectThis key takes a few common filters, just like in the IOS7 camera application, where the filters generally do not need to set any parameters (some of which can also be set up with different parameters), just the same as above, setting the Inputimage on the line. Print some of the filters in this category to see: I have selected one of the filters, which is a monochrome filter, although it looks a lot, but not complicated, Ciattributefilterdisplayname is its display name, Inputimage is the parameter, The details of each parameter are presented in a dictionary, including the type of the parameter (ciattributetypeimage), and the class of the parameter (Ciimage), followed by the category to which the filter belongs, and a filter can belong to more than one category at a time. The last is the string that the filter needs to provide when it is instantiated, that is, Ciphotoeffectmono. The above ciphotoeffectinstant and the following ciphotoeffectnoir, ciphotoeffectprocess and similar, all only need a inputimage parameter, is not very simple? The parameters of these filters have been set internally, so we can use them directly. For ease of use, we give Viewcontroller a cifilter attribute, instantiate the Cifilter in other methods, and use a common method to display the image after the filter is played:
Class Viewcontroller:uiviewcontroller {
@IBOutlet var imageview:uiimageview!
Lazy var originalimage:uiimage = {
Return UIImage (named: "Image")
}()
Lazy var context:cicontext = {
Return Cicontext (Options:nil)
}()
var filter:cifilter!
......
MARK:-Nostalgia
@IBAction func photoeffectinstant () {
Filter = Cifilter (name: "Ciphotoeffectinstant")
Outputimage ()
}
MARK:-Black and white
@IBAction func Photoeffectnoir () {
Filter = Cifilter (name: "Ciphotoeffectnoir")
Outputimage ()
}
MARK:-Hue
@IBAction func photoeffecttonal () {
Filter = Cifilter (name: "Ciphotoeffecttonal")
Outputimage ()
}
MARK:-Years
@IBAction func Photoeffecttransfer () {
Filter = Cifilter (name: "Ciphotoeffecttransfer")
Outputimage ()
}
MARK:-Monochrome
@IBAction func Photoeffectmono () {
Filter = Cifilter (name: "Ciphotoeffectmono")
Outputimage ()
}
MARK:-Faded
@IBAction func Photoeffectfade () {
Filter = Cifilter (name: "Ciphotoeffectfade")
Outputimage ()
}
MARK:-Stamping
@IBAction func photoeffectprocess () {
Filter = Cifilter (name: "Ciphotoeffectprocess")
Outputimage ()
}
MARK:-Chrome Yellow
@IBAction func photoeffectchrome () {
Filter = Cifilter (name: "Ciphotoeffectchrome")
Outputimage ()
}
Func Outputimage () {
println (Filter)
Let Inputimage = Ciimage (image:originalimage)
Filter.setvalue (Inputimage, Forkey:kciinputimagekey)
Let Outputimage = Filter.outputimage
Let Cgimage = Context.createcgimage (Outputimage, FromRect:outputImage.extent ())
Self.imageView.image = UIImage (cgimage:cgimage)
}
When these are all written, bind the various buttons and touch events on the UI, and the UI looks like this:
Various filter effects after running:
The above is the simple use of the core image built-in filter, which is sufficient if you do not need finer-grained control over the filter.
GitHub I'll keep up to date on GitHub.
UPDATED: I don't know if anyone noticed that I used it in the notes.//MARK:-, this and Objective-c's#pragma mark-function as well.
Resources:
Https://developer.apple.com/library/mac/documentation/graphicsimaging/conceptual/CoreImaging/ci_intro/ci_intro.html
IOS8 Core image in Swift: Automatically improve the use of images and built-in filters