any one help me to correct this code or help me my I have a graduation project coming soon

clear; close all; clc;
warning('off', 'all');
[contentFile, contentPath] = uigetfile({'*.bmp;*.jpg;*.png;*.tif', 'ملفات الصور'}, 'اختر صورة المحتوى');
if isequal(contentFile, 0)
error('لم يتم اختيار صورة محتوى');
end
contentImage = imread(fullfile(contentPath, contentFile));
[styleFile, stylePath] = uigetfile({'*.bmp;*.jpg;*.png;*.tif', 'ملفات الصور'}, 'اختر صورة النمط');
if isequal(styleFile, 0)
error('لم يتم اختيار صورة نمط');
end
styleImage = imread(fullfile(stylePath, styleFile));
contentImage = im2double(contentImage);
styleImage = im2double(styleImage);
if size(contentImage,3) == 1
contentImage = repmat(contentImage, [1 1 3]);
end
if size(styleImage,3) == 1
styleImage = repmat(styleImage, [1 1 3]);
end
styleImage = imadjust(styleImage, [0.1 0.9], []);
styleImage = imgaussfilt(styleImage, 1);
net = vgg19();
inputSize = net.Layers(1).InputSize(1:2);
% تغيير حجم الصور مع الحفاظ على التناسب
contentImage = imresize(contentImage, inputSize);
styleImage = imresize(styleImage, inputSize);
%% 4. تحديد الطبقات الصحيحة
contentLayer = 'conv4_2';
styleLayers = {'conv1_1', 'conv2_1', 'conv3_1', 'conv4_1', 'conv5_1'};
styleFeatures = getStyleFeatures(styleImage, net, styleLayers);
numIterations = 500;
learningRate = 0.01;
styleWeight = 1e6;
dlContent = dlarray(contentImage, 'SSC');
dlTransform = dlContent;
figure;
for iter = 1:numIterations
[grad, loss] = dlfeval(@computeGradients, dlTransform, dlContent, net, ...
contentLayer, styleLayers, styleFeatures, styleWeight);
dlTransform = dlTransform - learningRate * grad;
if mod(iter,50) == 0 || iter == 1
fprintf('التكرار %d: الخسارة الكلية=%.2f, المحتوى=%.2f, النمط=%.2f\n', ...
iter, loss.total, loss.content, loss.style);
% عرض التقدم
currentImg = uint8(extractdata(dlTransform)*255);
imshow(currentImg);
title(sprintf('التكرار %d/%d', iter, numIterations));
drawnow;
end
end
outputImage = uint8(extractdata(dlTransform)*255);
[~,name,ext] = fileparts(contentFile);
outputFile = fullfile(pwd, [name '_styled' ext]);
imwrite(outputImage, outputFile);
fprintf('تم حفظ الصورة الناتجة بنجاح في: %s\n', outputFile);
function features = getStyleFeatures(styleImg, net, styleLayers)
if ~ismatrix(styleImg) && ~(ndims(styleImg)==3)
error('يجب أن تكون صورة النمط مصفوفة 2D أو 3D');
end
if size(styleImg,3) ~= 3
error('يجب أن تحتوي صورة النمط على 3 قنوات لونية (RGB)');
end
try
dlStyle = dlarray(styleImg, 'SSC');
catch
error('فشل تحويل صورة النمط إلى dlarray');
end
features = struct();
for i = 1:length(styleLayers)
layer = styleLayers{i};
try
dlFeatures = activations(net, dlStyle, layer);
features.(layer) = computeGramMatrix(dlFeatures);
catch ME
error('فشل في استخراج خصائص الطبقة %s: %s', layer, ME.message);
end
end
end
function gramMatrix = computeGramMatrix(features)
[H,W,C] = size(features);
reshaped = reshape(features, H*W, C);
gramMatrix = reshaped' * reshaped / (H*W*C);
end
function [gradients, loss] = computeGradients(dlTransform, dlContent, net, ...
contentLayer, styleLayers, styleFeatures, styleWeight)
contentFeatures = activations(net, dlContent, contentLayer);
transformContentFeatures = activations(net, dlTransform, contentLayer);
contentLoss = mean((transformContentFeatures - contentFeatures).^2);
styleLoss = 0;
for i = 1:length(styleLayers)
layer = styleLayers{i};
transformFeatures = activations(net, dlTransform, layer);
gramTransform = computeGramMatrix(transformFeatures);
gramStyle = styleFeatures.(layer);
styleLoss = styleLoss + mean((gramTransform - gramStyle).^2);
end
styleLoss = styleLoss / length(styleLayers);
totalLoss = contentLoss + styleWeight * styleLoss;
gradients = dlgradient(totalLoss, dlTransform);
loss.total = double(totalLoss);
loss.content = double(contentLoss);
loss.style = double(styleLoss);
end
%%%%
erorr
rror using styletransfer>getStyleFeatures (line 111)
فشل في استخراج خصائص الطبقة conv1_1: Invalid 2-D image data. Specify image data as a 3-D numeric array containing a single image, a
4-D numeric array containing multiple images, a datastore, or a table containing image file paths or images in the first column.
Error in styletransfer (line 48)
styleFeatures = getStyleFeatures(styleImage, net, styleLayers);
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

댓글 수: 24

Looks like one of the arguments is not what it expects. What does this show in the command window?
whos styleImage
whos net
whos styleLayers
Name Size Bytes Class Attributes
styleImage 384x512x3 2359296 single
Name Size Bytes Class Attributes
net 1x1 576142857 SeriesNetwork
Name Size Bytes Class Attributes
styleLayers 1x5 670 cell
Please attach your 2 images to your post so we can test your code. You can attach them using the paperclip icon.
styleImage 384x512x3 2359296 single
I wonder if the problem is that styleImage is datatype single instead of uint8 or double ?
Good point/possibility, @Walter Roberson
@osama unless you know for a fact that your network requires floating point images, comment out these two lines
contentImage = im2double(contentImage);
styleImage = im2double(styleImage);
and see how it goes.
this is m images the style image and content image i need to train AI to transfer this style too image content I spent too match hours for this code and I did not have an result please help me I have 216 style images this is cods after 1000 iteration the same result what I can do
%% Load Content Image and Select Style Folder
[contentFile, contentPath] = uigetfile('*.bmp', 'Choose Content Image');
Error using uigetfile (line 117)
Support for Java user interfaces is required, which is not available on this platform.
if contentFile == 0
error('No content image was chosen. Make sure to select a valid image file.');
end
contentImage = imresize(single(imread(fullfile(contentPath, contentFile))), [224, 224]);
% Choose Style Folder
styleFolder = uigetdir('', 'Choose Style Folder');
if styleFolder == 0
error('No folder was chosen. Make sure to select a valid style image folder.');
end
% Load Style Images
styleFiles = dir(fullfile(styleFolder, '*.bmp'));
styleImages = cell(1, numel(styleFiles));
for i = 1:numel(styleFiles)
styleImages{i} = imresize(single(imread(fullfile(styleFolder, styleFiles(i).name))), [224, 224]);
end
%% Enhanced Network Settings
inputSize = [224, 224, 3];
% Build VGG-19 Model with Enhanced Feature Extraction
layers = [
imageInputLayer(inputSize, 'Name', 'input', 'Normalization', 'none')
% Block 1
convolution2dLayer(3, 96, 'Padding', 'same', 'Name', 'conv1_1') % Increased to 96 filters
reluLayer('Name', 'relu1_1')
convolution2dLayer(3, 96, 'Padding', 'same', 'Name', 'conv1_2')
reluLayer('Name', 'relu1_2')
maxPooling2dLayer(2, 'Stride', 2, 'Name', 'pool1')
% Block 2
convolution2dLayer(3, 192, 'Padding', 'same', 'Name', 'conv2_1') % Increased to 192 filters
reluLayer('Name', 'relu2_1')
convolution2dLayer(3, 192, 'Padding', 'same', 'Name', 'conv2_2')
reluLayer('Name', 'relu2_2')
maxPooling2dLayer(2, 'Stride', 2, 'Name', 'pool2')
% Block 3
convolution2dLayer(3, 384, 'Padding', 'same', 'Name', 'conv3_1') % New layer
reluLayer('Name', 'relu3_1')
convolution2dLayer(3, 384, 'Padding', 'same', 'Name', 'conv3_2') % New layer
reluLayer('Name', 'relu3_2')
];
net = dlnetwork(layers);
%% Enhanced Training Parameters
numIterations = 2000;
learningRate = 1e-3;
contentWeight = 1e4;
styleWeight = 1e6;
% Layers for enhanced feature extraction
contentLayer = "conv3_2"; % Use deeper layer
styleLayers = ["conv1_1", "conv1_2", "conv2_1", "conv2_2", "conv3_1", "conv3_2"]; % More style layers
%% Calculate Style Features for Each Style Image Separately
styleFeatures = cell(1, numel(styleLayers));
for i = 1:numel(styleFiles)
img = dlarray(styleImages{i}, 'SSCB');
for j = 1:numel(styleLayers)
features = stripdims(forward(net, img, 'Outputs', styleLayers(j)));
[h,w,c] = size(features);
features = reshape(features, h*w, c);
% Calculate Gram matrix
gramMatrix = (features' * features) / (h * w * c);
gramMatrix = extractdata(gramMatrix);
gramMatrix = gramMatrix / norm(gramMatrix, 'fro'); % Now gramMatrix is double
if isempty(styleFeatures{j})
styleFeatures{j} = gramMatrix;
else
styleFeatures{j} = styleFeatures{j} + gramMatrix;
end
end
end
% Calculate average and final normalization
for j = 1:numel(styleLayers)
styleFeatures{j} = styleFeatures{j} / numel(styleImages);
end
%% Improved Training Process
% Start with the content image rather than random noise
generatedImage = dlarray(contentImage + randn(size(contentImage))*0.1, 'SSCB');
% Enhanced Adam settings
avgGrad = [];
avgSqGrad = [];
decay = 0.85;
sqDecay = 0.99;
tvWeight = 50; % TV loss weight to improve smoothness
for iter = 1:numIterations
% Randomly select content image
contentImage = dlarray(contentImage, 'SSCB');
% Compute gradients with total variation loss
[grad, totalLoss, contentLoss, styleLoss, tvLoss] = dlfeval(...
@computeGradients, net, generatedImage, contentImage, styleFeatures, ...
contentLayer, styleLayers, contentWeight, styleWeight, tvWeight);
% Diminishing learning rate
currentLR = learningRate * (1 - iter/numIterations)^0.5;
[generatedImage, avgGrad, avgSqGrad] = adamupdate(...
generatedImage, grad, avgGrad, avgSqGrad, iter, ...
currentLR, decay, sqDecay);
% Display enhanced progress
if mod(iter,10) == 0
fprintf('Iter %4d: Loss=%.2f (Content=%.2f, Style=%.2f, TV=%.2f)\n', ...
iter, extractdata(totalLoss), extractdata(contentLoss), ...
extractdata(styleLoss), extractdata(tvLoss));
if mod(iter,100) == 0 || iter == 1
img = extractdata(generatedImage);
img = rescale(img);
% Improve contrast
img = imadjust(img, stretchlim(img, [0.01, 0.99]));
figure(1);
imshow(img);
title(sprintf('Iteration %d', iter));
drawnow;
% Save the image with improved quality
imwrite(img, sprintf('output_%04d.bmp', iter));
end
end
end
%% Enhanced Helper Functions
function [grad, totalLoss, contentLoss, styleLoss, tvLoss] = computeGradients(...
net, generatedImage, contentImage, styleFeatures, contentLayer, ...
styleLayers, contentWeight, styleWeight, tvWeight)
generatedImage = dlarray(generatedImage, 'SSCB');
% Content loss
contentFeatures = forward(net, contentImage, 'Outputs', contentLayer);
genContentFeatures = forward(net, generatedImage, 'Outputs', contentLayer);
contentLoss = contentWeight * mean((genContentFeatures - contentFeatures).^2, 'all');
% Style loss
styleLoss = dlarray(0);
for j = 1:numel(styleLayers)
features = stripdims(forward(net, generatedImage, 'Outputs', styleLayers(j)));
[h,w,c] = size(features);
features = reshape(features, h*w, c);
gramMatrix = (features' * features) / (h*w*c);
styleLoss = styleLoss + styleWeight * mean((gramMatrix - styleFeatures{j}).^2, 'all') / numel(styleLayers);
end
% Total Variation Loss (for better smoothness)
diff1 = generatedImage(:,1:end-1,:,:) - generatedImage(:,2:end,:,:);
diff2 = generatedImage(1:end-1,:,:,:) - generatedImage(2:end,:,:,:);
tvLoss = tvWeight * (mean(diff1.^2, 'all') + mean(diff2.^2, 'all'));
% Total loss
totalLoss = contentLoss + styleLoss + tvLoss;
% Gradients
grad = dlgradient(totalLoss, generatedImage, 'RetainData', true);
end
I did everything I could to transfer the image but nothing happened,It is the last model for the graduation project, but I failed in it
Your code is for bmp files, but you have posted two jpg images and no bmp images.
It is not clear which image is intended to be the "Content" image.
Yes I'm convert it becouse the images size large to load
It is not clear which image is intended to be the "Content" image. It is not clear which images are intended to be within the style folder.
I'm soory the style image is 25319 f qlf
I am running the code now. It is taking a fair while.
I made the qlf file into a bmp file and put it inside a directory named "styles".
I made the non-qlf file into a bmp file, and gave the name of that file in response to the uigetfile()
The code ran without producing any error messages. It tooks more than an hour to run on my machine.
At this point, I do not know what I should be looking for?
Note: I ran on R2025a Pre-release on an intel iMac.
Is there any transfer of style?
Can you give any account to contact you please?

I do not know what to look for to determine whether there is transfer of style, but the final image did not have noticeable mixing of the other image.

I prefer to handle discussions in public.

I want the style to be transferred, even if it is similar, but it does not have to be 100%. Even if it is 80% transfer of the style in order for it to be accepted, what are the modifications that can be made?
If I imresize() the original image to be the same size as the output image, then I am able to compare the output image to the original image. The output image has slightly different lighting compared to the input image -- a little pinker, less stark white.
I do not understand what it means for the "style" to be "transferred".
Is the idea that you want to end up with the teeth isolated and the gums dimmed out? I don't think your current code attempts that; your current code does not attempt to isolate the teeth, and so could easily find "features" in the gums area.
Transfer the style properties to the regular image so that the regular image becomes the style image.
That makes it sounds as if you just want to copy the style image to the regular image.
What is it about the style image that you want merged with the regular image? Saying "the style properties" is too general.
This is the doctor's request
No-one is going to be able to assist you unless you explain what it means to you to "transfer style properties" .
Are you trying to end up with the teeth unchanged but the gums a monochrome red ?

댓글을 달려면 로그인하십시오.

답변 (0개)

카테고리

질문:

2025년 4월 27일

댓글:

2025년 5월 5일

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by