1 /**
2 * Copyright 2020 Huawei Technologies Co., Ltd
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #include "minddata/dataset/kernels/image/sharpness_op.h"
18 #include "minddata/dataset/kernels/image/image_utils.h"
19 #include "minddata/dataset/core/cv_tensor.h"
20 #include "minddata/dataset/util/status.h"
21
22 namespace mindspore {
23 namespace dataset {
24
25 const float SharpnessOp::kDefAlpha = 1.0;
26
Compute(const std::shared_ptr<Tensor> & input,std::shared_ptr<Tensor> * output)27 Status SharpnessOp::Compute(const std::shared_ptr<Tensor> &input, std::shared_ptr<Tensor> *output) {
28 IO_CHECK(input, output);
29
30 try {
31 std::shared_ptr<CVTensor> input_cv = CVTensor::AsCVTensor(input);
32 cv::Mat input_img = input_cv->mat();
33 if (!input_cv->mat().data) {
34 RETURN_STATUS_UNEXPECTED("[Internal ERROR] Sharpness: load image failed.");
35 }
36
37 if (input_cv->Rank() == 1 || input_cv->mat().dims > 2) {
38 RETURN_STATUS_UNEXPECTED("Sharpness: shape of input is not <H,W,C> or <H,W>, but got rank: " +
39 std::to_string(input_cv->Rank()));
40 }
41
42 /// creating a smoothing filter. 1, 1, 1,
43 /// 1, 5, 1,
44 /// 1, 1, 1
45
46 const float filterMid = 5.0;
47 const float filterSum = 13.0;
48 cv::Mat filter = cv::Mat(3, 3, CV_32F, cv::Scalar::all(1.0 / filterSum));
49 filter.at<float>(1, 1) = filterMid / filterSum;
50
51 /// applying filter on channels
52 cv::Mat result = cv::Mat();
53 cv::filter2D(input_img, result, -1, filter);
54
55 int height = input_cv->shape()[0];
56 int width = input_cv->shape()[1];
57
58 /// restoring the edges
59 input_img.row(0).copyTo(result.row(0));
60 input_img.row(height - 1).copyTo(result.row(height - 1));
61 input_img.col(0).copyTo(result.col(0));
62 input_img.col(width - 1).copyTo(result.col(width - 1));
63
64 /// blend based on alpha : (alpha_ *input_img) + ((1.0-alpha_) * result);
65 cv::addWeighted(input_img, alpha_, result, 1.0 - alpha_, 0.0, result);
66
67 std::shared_ptr<CVTensor> output_cv;
68 RETURN_IF_NOT_OK(CVTensor::CreateFromMat(result, input_cv->Rank(), &output_cv));
69 RETURN_UNEXPECTED_IF_NULL(output_cv);
70
71 *output = std::static_pointer_cast<Tensor>(output_cv);
72 }
73
74 catch (const cv::Exception &e) {
75 RETURN_STATUS_UNEXPECTED("Sharpness: " + std::string(e.what()));
76 }
77 return Status::OK();
78 }
79 } // namespace dataset
80 } // namespace mindspore
81